I have written the below code which is working, there is no compilation error. I am successfully getting the uploaded images printed in the console. But just after uploading the image, its not visible in the page. I need to click anywhere on the screen ,then the images get previewed in the screen.
onFileChange(event) {
if (event.target.files && event.target.files[0]) {
var filesAmount = event.target.files.length;
for (let i = 0; i < filesAmount; i++) {
var reader = new FileReader();
reader.readAsDataURL(event.target.files[i]);
reader.onload = (event: any) => {
this.images.push(event.target.result);
};
}
}
}
<form [formGroup]="formGroup" (ngSubmit)="submit()">
<section>
<h3 class="fs-20 fw-600 text-color9 mb-30">
Step 4: Sample information
</h3>
<div class="samples d-flex flex-wrap mb-5">
<div class="sample-item mb-3 mb-lg-0">
<div
class="upload-box rounded-4 bg-white position-relative d-flex justify-content-center align-items-center flex-column overflow-hidden"
>
<input
id="file"
type="file"
class="form-control"
accept="image/*"
(change)="onFileChange($event)"
/>
<i class="icon-plus fs-36 text-color4 mb-2"></i>
<h6 class="fs-18 fw-500 text-color4 mb-0">Upload image</h6>
</div>
</div>
<div class="sample-item mb-3 mb-lg-0">
<div class="image-box">
<img class="rounded-4" *ngFor="let url of images" [src]="url" />
<br />
</div>
</div>
</div>
//other formgoup inputs will be written here
<div class="action-button pb-3">
<hr />
<div class="text-end">
<button
type="button"
class="btn btn-sm btn-primary-outline me-3"
routerLink="/order/create-order"
[queryParams]="{ id: orderObject?.orderID }"
>
Back
</button>
<button type="submit" class="btn btn-sm btn-primary">
Continue
</button>
</div>
</div>
</section>
</form>
Every time I click choose file in the this.image the images get inserted. If I try to runconsole.log(this.images) it also gets printed . But its not immediately rendered in the screen by this array this.images via *ngFor
When this ts code is run in https://stackblitz.com/edit/angular-file-upload-preview?file=app%2Fapp.component.ts its running fine. Just after choosing file the image get visible in the screen.
Please help me to know what is the reason behind such behavior.
>Solution :
You might need to run the angular cycle again. try
constructor(
private cdr: ChangeDetectorRef
) {}
reader.onload = (event: any) => {
this.images.push(event.target.result);
this.cdr.detectChanges();
};