[英]How to solve the "Expression Changed After It Has Been Checked Error" in Angular?
我想在 Angular 中實現一個聊天。 聊天的每個項目(消息)都有一個標題(標題/名稱),應該有一個特定的邊距。 邊距應根據 div 的高度計算。 代碼看起來像這樣。
<div *ngFor="let item of chatArray">
<div #juliet [style.margin-top.px]= "-(juliet.clientHeight/2)">
{{item.message}}
</div>
</div>
問題出在 Chrome 瀏覽器中(在 Mozilla 中沒有問題)。 控制台錯誤是:“ExpressionChangedAfterItHasBeenCheckedError:檢查后表達式已更改。以前的值:'margin-top:-40.5'。當前值:'margin-top:-40'。”。
在 ts 文件中,我嘗試實現更改檢測:
ngOnInit() {
//code for chat initialization
this.cdRef.detectChanges();
}
ngAfterViewInit() {
this.cdRef.detectChanges();
}
ngAfterContentChecked() {
this.cdRef.detectChanges();
}
如果我添加 .ts 文件
@Component({
...
changeDetection: ChangeDetectionStrategy.OnPush
})
錯誤消失,但邊距小於應有的值。 我想擺脫錯誤並根據 div 高度計算右邊距。
我會很感激你的任何想法。 謝謝!
ngOnInit() .detectChanges 調用是無用的,因為更改檢測正在進行中,並且在評估 ngOnInit 鈎子后將檢查模板。
ngAfterViewInit 和 ngAfterContentChecked .detectChanges 調用是錯誤的,因為這些鈎子是在使用正確的數據更新模板后調用的。
嘗試一些東西,可能會解決這個問題。 創建指令
import { Directive, ElementRef } from '@angular/core';
@Directive({
selector: '[appApplyMargin]'
})
export class ApplyMargin {
constructor(el: ElementRef) {
el.nativeElement.style.marginTop =
(el.nativeElement.clientHeight/2) + 'px'
}
}
注意:如果需要將構造函數中的代碼包裝在setTimeout
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.