How can I preview multiple images that I have selected before uploading them in Angular?
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]);
}
}
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);
}
}
}
}
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