html 在激活[(ngModel)]之前等待数据加载

9rnv2umw  于 2022-12-09  发布在  其他
关注(0)|答案(2)|浏览(102)

我在component.html-file中有以下代码,它会触发一个错误:

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

错误:TypeError: Cannot read properties of undefined (reading 'ignoreHolidays')
我假设,[(ngModel)]尝试在ignoreHolidays被赋值之前读取它的值。
我的组件.ts文件在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);
      })
    )
  }

我的html-file中的所有其他值都已设置,调用按预期工作。
[(ngModel)]尝试读取数据之前,如何确保this.ignoreHolidaysObject已被分配数据?

6ojccjat

6ojccjat1#

您可以使用一些虚拟数据示例化ignoreHolidaysObject,以便在异步数据到达之前成功设置绑定,例如:
.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>

也可以简单地阻止组件呈现,直到对象被填充并准备好绑定为止
.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>
htrmnn0y

htrmnn0y2#

将*ngIf=“ignoreHolidaysObject”添加到垫子幻灯片切换

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

相关问题