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

Time:12-06

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.

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?

CodePudding user response:

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>

CodePudding user response:

Add *ngIf="ignoreHolidaysObject" to mat-slide-toggle :

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