Home > Mobile >  Uploaded image in angular 7 not displayed just after upload
Uploaded image in angular 7 not displayed just after upload

Time:10-19

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 >
          Step 4: Sample information
        </h3>
        <div >
          <div >
            <div
              
            >
              <input
                id="file"
                type="file"
                
                accept="image/*"
                (change)="onFileChange($event)"
              />

              <i ></i>
              <h6 >Upload image</h6>
            </div>
          </div>
          <div >
            <div >
              <img  *ngFor="let url of images" [src]="url" />
              <br />
            </div>
          </div>
        </div>

//other formgoup inputs will be written here

        <div >
          <hr />
          <div >
            <button
              type="button"
              
              routerLink="/order/create-order"
              [queryParams]="{ id: orderObject?.orderID }"
            >
              Back
            </button>
            <button type="submit" >
              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/app.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.

CodePudding user response:

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();         
  };
  • Related