Angular 4.4 - ExpressionChangedAfterItHasBeenCheckedError

时间:2017-10-06 10:52:33

标签: javascript angular

我已将其简化为最简单的形式,如下所示:

<select (change)="switch()" [hidden]="visible" [(ngModel)]="model">
  <option *ngFor="let amount of [1,2,3]" [ngValue]="amount"> {{amount}} </option>
</select>

<div [hidden]="!visible">... we swap places</div>
export class SomeComponent {

  model = 1;
  visible = false;

  switch() {
    if (this.visible === 3) {
    this.visible = true;
  }

}

这似乎工作正常,但它也会抛出:ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'true'. Current value: 'false'.

如何在此处检查之前更改它?

1 个答案:

答案 0 :(得分:1)

您可以通过明确触发更改来处理此问题,

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

constructor(private cdr: ChangeDetectorRef) {}

switch() {
    if (this.visible === 3) {
      this.visible = true;
      this.cdr.detectionChanges();
      ...
}