I've been trying to get an image to appear from a URL input in Typescript but have only been able to do it in javascript. When user inserts image URL a preview should show up and be able to upload it. I apologize for not having more code just haven't been able to figure it out..
upload.component.html
input type="URL" id="myURL" placeholder="insert image URL here" (change)="onURLinserted($event) ">
<button type="button" class="btn btn-dark btninput" [disabled]="toogleBool" (click)="onUpload()">Upload</button>
upload.component.ts
onURLinserted(event: any) {
}
Here is answer for you, Iam used two way data binding for access to your image url. And also used property binding in image tag for bind your image.
Html File,
<input type="URL" name="myURL" [(ngModel)]="myURL" placeholder="insert image URL here" (change)="onURLinserted() ">
<img [src]="imageToShow" alt="Place image title">
Typescript File,
imageToShow:any;
myURL:any
onURLinserted() {
this.getImage(myURL).subscribe(data => {
this.createImageFromBlob(data);
}, error => {
console.log("Error occured",error);
});
}
getImage(imageUrl: string): Observable<File> {
return this.http
.get(imageUrl, { responseType: ResponseContentType.Blob })
.map((res: Response) => res.blob());
}
createImageFromBlob(image: Blob) {
let reader = new FileReader(); //you need file reader for read blob data to base64 image data.
reader.addEventListener("load", () => {
this.imageToShow = reader.result; // here is the result you got from reader
}, false);
if (image) {
reader.readAsDataURL(image);
}
}
For more details visit this link.
Getting Image from API in Angular 4?
I hope it's helpful to sovle your problem.
Edit:-
import { Http,ResponseContentType } from '@angular/http';
constructor(private http: Http){}
getImage(imageUrl: string): Observable<File> {
let headers={ responseType: ResponseContentType.Blob }
return this.http
.get(imageUrl, headers)
.map((res: Response) => res.blob());
}
let try this once again,
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With