ViewChildren
などを利用すると ngAfterViewInit
などで変数に値を入れてそれをViewで利用することがある。
この場合、 html
内で *ngIf="component"
のようにその変数が生成されるまで待ちたいと考えるだろう。
このとき、こんなエラーが Console
上に表示される。
EXCEPTION: Expression has changed after it was checked
どうも、 ngAfterViewInit()
などで変数を変更したら起きるらしい(Prod mode だと起きないとかなんとか)。
エラーが出るだけで特に問題なく動くのだが、Consoleにエラーが出るのがうざったいので対処方法を記載。
Component側の対処方法↓
.ts
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の例↓
.html
<div *ngIf="ko1">
testです。
</div>