yavg
yavg

Reputation: 3051

my ngmodel does not reload, the binding is not working

Actually this code is from ionic, and I am processing an image that I get through the photo capture. everything works fine, I get the blob, but for some reason my image is not shown in the template, I think the angular binding is not updating. What can I do to force it?

    myblob:any=null;
    takePhoto() {
        const options: CameraOptions = {
        quality: 60,
        destinationType: this.camera.DestinationType.FILE_URI,
        encodingType: this.camera.EncodingType.JPEG,
        mediaType: this.camera.MediaType.PICTURE,
        allowEdit: true,
        };

        this.camera.getPicture(options).then(
        (imageData) => {
            this.file
            .resolveLocalFilesystemUrl(imageData)
            .then((entry: FileEntry) => {
                entry.file((file) => {
                    this.readFile(file);
                });
            });
        },
        (err) => {
            // Handle error
        }
        );
    }


    readFile(file: any) {
        const reader = new FileReader();
        reader.onloadend = () => {
        const imgBlob = new Blob([reader.result], {
            type: file.type,
        });
            //my ngModel (updating)   ****------------->
            this.myblob = URL.createObjectURL(imgBlob);
            console.log(this.documento_reverso);
        };
        reader.readAsArrayBuffer(file);
    }

In my template:

    <button (click)="takePhoto()">Take photo</button>
    <img *ngIf="myblob" [src]="myblob">  --> is not show at first time button click

how can do it?

When I click the button and get the photo, the image is not displayed, but the second time I click the button it is immediately displayed.

Upvotes: 1

Views: 97

Answers (1)

Martin Parenteau
Martin Parenteau

Reputation: 73721

You can wrap the code in NgZone.run to make sure that it runs in the Angular zone and that the change is picked up by change detection:

import { NgZone } from '@angular/core';

constructor(private ngZone: NgZone) { }

readFile(file: any) {
  ...
  this.ngZone.run(() => {
    this.myblob = URL.createObjectURL(imgBlob);
  });
  ...
}

Upvotes: 3

Related Questions