[Angular] (EXCEPTION: Expression has changed after it was checked) の対応方法 (Angular2, 4, 5)


ViewChildren などを利用すると ngAfterViewInit などで変数に値を入れてそれをViewで利用することがある。
この場合、 html 内で *ngIf="component" のようにその変数が生成されるまで待ちたいと考えるだろう。

このとき、こんなエラーが Console 上に表示される。

EXCEPTION: Expression has changed after it was checked

どうも、 ngAfterViewInit() などで変数を変更したら起きるらしい(Prod mode だと起きないとかなんとか)。
エラーが出るだけで特に問題なく動くのだが、Consoleにエラーが出るのがうざったいので対処方法を記載。

Component側の対処方法↓

export class TestComponent {
  @ViewChildren(KoComponents): koComponents: QueryList<KoComponents>;
  ko1: KoComoponent;
  constructor(private changeDetectionRef: ChangeDetectorRef) {}

  ngViewInit(): void {
    this.ko1 = koComponents.toArrays()[0];
    this.changeDetectionRef.detectChanges();
  }
}

Viewの例↓

<div *ngIf="ko1">
  testです。
</div>

参考
https://github.com/angular/angular/issues/6005