3

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) {

}
Charlie Batista
  • 125
  • 1
  • 2
  • 8

1 Answers1

3

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,

Karnan Muthukumar
  • 1,843
  • 1
  • 8
  • 15
  • Thank you for you answer. I keep getting error Types of property 'responseType' are incompatible. Type 'ResponseContentType' is not assignable to type '"json"'. in .get(imageUrl, { responseType: ResponseContentType.Blob }) – Charlie Batista Jul 13 '18 at 15:13
  • Iam updated my answer please check and use like this. – Karnan Muthukumar Jul 13 '18 at 17:48