我想在 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 高度計算右邊距。
我會很感激你的任何想法。謝謝!
uj5u.com熱心網友回復:
嘗試一些東西,可能會解決這個問題。創建指令
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
uj5u.com熱心網友回復:
ngOnInit() .detectChanges 呼叫是無用的,因為更改檢測正在進行中,模板將在評估 ngOnInit 鉤子后立即檢查。
ngAfterViewInit 和 ngAfterContentChecked .detectChanges 呼叫是錯誤的,因為這些鉤子是在使用正確的資料更新模板后呼叫的。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/346334.html
上一篇:在物體類中存盤多個地址欄位
