Joseph
Joseph

Reputation: 7755

Previewing Multiple Image and Video in Angular

I have a problem with previewing multiple image and videos in my Angular app. I have the "format" variable to determine if it is an "image" or "video".

Stackblitz

export class AppComponent {
  urls;
  format;

  onSelectFile(event) {
    const files = event.target.files;
    if (files) {
      for (const file of files) {
        if (file.type.indexOf("image") > -1) {
          this.format = "image";
        } else if (file.type.indexOf("video") > -1) {
          this.format = "video";
        }

        const reader = new FileReader();
        reader.onload = (e: any) => {
          this.urls.push(e.target.result);
        };
        reader.readAsDataURL(file);
      }
    }
  }
}

Upvotes: 0

Views: 990

Answers (1)

Maihan Nijat
Maihan Nijat

Reputation: 9355

You have urls variable but not initialized. It throws an error when you push elements to undefined variable. To fix this, you need to initialize the variable like:

urls = [];

Update: Add images and videos in a seperate arrays and loop through then:

export class AppComponent {
  imageUrls = [];
  videoUrls = [];
  onSelectFile(event) {
    const files = event.target.files;
    if (files) {
      for (const file of files) {
        const reader = new FileReader();
        reader.onload = (e: any) => {
          if (file.type.indexOf("image") > -1) {
            this.imageUrls.push(e.target.result);
          } else if (file.type.indexOf("video") > -1) {
            this.videoUrls.push(e.target.result);
          }
        };
        reader.readAsDataURL(file);
      }
    }
  }
}

And this is how you display:

<ng-container>
    <img *ngFor="let url of imageUrls" [src]="url" />
</ng-container>

<ng-container>
    <video *ngFor="let url of videoUrls" [src]="url" controls></video>
</ng-container>

Upvotes: 1

Related Questions