【问题标题】:Mat-select with *ngIf causing ExpressionChangedAfterItHasBeenCheckedError使用 *ngIf 进行 Mat-select 导致 ExpressionChangedAfterItHasBeenCheckedError
【发布时间】:2019-12-19 21:49:26
【问题描述】:

我有一个 mat-form-field 我想包含一个输入或一个选择。

当我使用 时,*ngIf 工作正常。但是,当我使用下面的 时,它会抛出“ExpressionChangedAfterItHasBeenCheckedError”。

我认为这只是在我将 Angular 版本更新为:

Angular CLI:8.2.1 节点:10.16.2 角度:9.0.0-next.1

为什么它应该使用输入而不是选择?

这里是html:

<mat-form-field>
  <input *ngIf="input.name!=='Bid'" matInput [(ngModel)]="input.value">
  <mat-select *ngIf="input.name==='Bid'" [(value)]="input.value">
    <mat-option *ngFor="let s of statuses" name="status" [value]="s">{{s}}</mat-option>
  </mat-select>
  <mat-placeholder class="placeholder">{{input.name}}</mat-placeholder>
</mat-form-field>

input.name 属性在 ngOnInit() 中调用的方法中设置,如下所示:

ngOnInit() {
  this.prepareInputs();
}

【问题讨论】:

  • prepareInputs方法是否异步加载数据?
  • @Scorpioo590 不。它们只是对来自父组件的输入进行的计算。本质上是添加到现有对象的额外字段
  • 当您将this.prepareInputs();ngOnInit 移动到ngAfterViewInit 时会发生什么?
  • @Stavm 我解决了这个问题。这是由 &lt;mat-placeholder&gt; 没有应用相同的 *ngIf 引起的。这导致它闲逛并与&lt;mat-select&gt;

标签: angular angular-material2


【解决方案1】:

这是由&lt;mat-placeholder&gt; 行引起的,它没有应用*ngIf,所以当没有选择输入时,&lt;mat-placeholder&gt; 导致事情卡住了!当我将*ngIf 放在&lt;mat-placeholder&gt; 上时,问题就消失了。

<mat-form-field>
  <input *ngIf="input.name!=='Bid'" matInput [(ngModel)]="input.value">
  <mat-placeholder *ngIf="input.name!=='Bid'" class="placeholder">{{input.name}}</mat-placeholder>
  <mat-select *ngIf="input.name==='Bid'" [(value)]="input.value">
    <mat-option *ngFor="let s of statuses" name="status" [value]="s">{{s}}</mat-option>
  </mat-select>
</mat-form-field>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-06-07
    • 1970-01-01
    • 2019-07-03
    • 1970-01-01
    • 1970-01-01
    • 2021-09-15
    • 2013-04-04
    • 2020-08-20
    相关资源
    最近更新 更多