LoginSignup
5
3

More than 5 years have passed since last update.

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

Last updated at Posted at 2018-02-04

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

5
3
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
3