![](/img/trans.png)
[英]ExpressionChangedAfterItHasBeenCheckedError with ngClass and no child component
[英]ExpressionChangedAfterItHasBeenCheckedError with ngClass
我有兩個錨標簽
<ul class="switchNav">
<li [ngClass]="!hidePanel2 ? 'active' : ''">
<a href="javascript:void(0)" (click) ="hideShowPanel(1)">panel 1</a>
</li>
<li [ngClass]="!hidePanel1? 'active' : ''">
<a href="javascript:void(0)" (click) ="hideShowPanel(2)">panel 2</a>
</li>
</ul>
.ts
hidePanel2: boolean = true;
hidePanel1: boolean = false;
hideShowPanel(check: number) {
if (check == 1) {
this.hidePanel2 = true;
this.hidePanel1 = false;
}
else {
this.hidePanel1 = false;
this.hidePanel2 = true;
}
}
當我單擊錨標記時,它會引發錯誤
ExpressionChangedAfterItHasBeenCheckedError
它正在工作,但由於團隊成員更新任何模塊,它停止工作,
我用谷歌搜索了很多,但無法讓它工作
請幫忙
謝謝
要添加 Ritesh 的答案,在這種情況下,您可以做兩件事:
setTimeout()
回調中——
constructor(private changeDetector: ChangeDetectorRef) {
}
hideShowPanel(check: number) {
if (check == 1) {
this.hidePanel2 = true;
this.hidePanel1 = false;
}
else {
this.hidePanel1 = false;
this.hidePanel2 = true;
}
this.changeDetector.detectChanges();
}
我還想推薦一篇有趣的文章,它解釋了幕后發生的事情: 您需要了解的有關 ExpressionChangedAfterItHasBeenCheckedError 的所有信息
像這樣修改你的方法:
hideShowPanel(check: number) {
setTimeout( ()=> {
if (check == 1) {
this.hidePanel2 = true;
this.hidePanel1 = false;
}
else {
this.hidePanel1 = false;
this.hidePanel2 = true;
}
}, 0);
}
基本上,ExpressionChangedAfterItHasBeenCheckedError 在更改檢測運行時發生,之后表達式值被修改。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.