Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Wait for data to have loaded before [(ngModel)] is activated

I have the following code in a component.html-file, that triggers an error:

<mat-slide-toggle [(ngModel)]="ignoreHolidaysObject.ignoreHolidays">
    Ignore holidays
</mat-slide-toggle>

ERROR: TypeError: Cannot read properties of undefined (reading 'ignoreHolidays')

I assume, that [(ngModel)] tries to read the value of ignoreHolidays before it has been assigned a value.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

My component.ts file has the following in ngOnInit:

ngOnInit(): void {
    this.subs.add(this._ignoreHolidaysService.getIgnoreHolidaysResult() //subs is subsink
      .subscribe((__ignoreHolidaysObject: IgnoreHolidaysViewModel) => {
        this.ignoreHolidaysObject = __ignoreHolidaysObject;
      },
      (error: HttpErrorResponse) => {
        console.log("Call threw an error", error);
      })
    )
  }

All other values in my html-file are set and the call works as intended.

How do I ensure, that this.ignoreHolidaysObject has been assigned data, before [(ngModel)] tries to read from it?

>Solution :

You can either instantiate ignoreHolidaysObject with some dummy data to allow the binding to be setup successfully prior to your asynchronous data arriving, e.g.

.ts

ignoreHolidaysObject = {
  ignoreHolidays: null  // choose a suitable "empty" value for your  use case
}

.html

<mat-slide-toggle [(ngModel)]="ignoreHolidaysObject.ignoreHolidays">
    Ignore holidays
</mat-slide-toggle>

or you can simply prevent the component from being rendered until your object has been populated and is thus ready to be bound

.html

<mat-slide-toggle
    *ngIf="ignoreHolidaysObject"
    [(ngModel)]="ignoreHolidaysObject.ignoreHolidays">
    Ignore holidays
</mat-slide-toggle>

or

<mat-slide-toggle
    *ngIf="ignoreHolidaysObject?.ignoreHolidays"
    [(ngModel)]="ignoreHolidaysObject.ignoreHolidays">
    Ignore holidays
</mat-slide-toggle>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading