Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Preview multiple image before upload file in Angular

How can I preview multiple images that I have selected before uploading them in Angular?

enter image description here

I have managed to do it but only with one image, even though I select several, only one recognizes me. I think the use of *ngFor is a good alternative but I'm not sure how to raise it. Any ideas?

myComponent.html

<img *ngIf="url" [src]="url" class="rounded mb-3" width="180">
<input type="file" multiple (change)="detectFiles($event)">

myComponent.ts

detectFiles(event) {
this.selectedFiles = event.target.files;
if (event.target.files && event.target.files[0]) {
  var reader = new FileReader();
  reader.onload = (event: any) => {
    this.url = event.target.result;
  }
  reader.readAsDataURL(event.target.files[0]);
}
}
like image 414
Paco Zevallos Avatar asked Feb 23 '18 01:02

Paco Zevallos


1 Answers

As shown in this stackblitz, you can store the image URLs in an array and display them with ngFor:

<div>
    <img *ngFor="let url of urls" [src]="url" class="rounded mb-3" width="180">
</div>
<input type="file" multiple (change)="detectFiles($event)">

The array of URLs is filled in detectFiles:

export class AppComponent {

  urls = new Array<string>();

  detectFiles(event) {
    this.urls = [];
    let files = event.target.files;
    if (files) {
      for (let file of files) {
        let reader = new FileReader();
        reader.onload = (e: any) => {
          this.urls.push(e.target.result);
        }
        reader.readAsDataURL(file);
      }
    }
  }
}
like image 70
ConnorsFan Avatar answered Oct 14 '22 17:10

ConnorsFan