我有一個帶有客戶端屬性的組件。
import { Component } from '@angular/core';
@Component({
selector: 'app-update-view',
templateUrl: './update-view.component.html',
styles: [
]
})
export class UpdateView {
public client: string[] = ['client 1', 'client 2', 'client 3', 'client 4'];
constructor() { }
deleteClient() {
this.client.pop();
}
}
在 html 中,我像這樣列印物件。
<div class="col md:col-6">
<div>
<strong>Client</strong>
<pre>{{ Client }}</pre>
</div>
<button (click)="deleteClient()">Delete Client</button>
</div>
我知道這不是列印陣列的方法,我應該使用 'ngFor 并一個一個列印專案,但我想知道是否有辦法在洗掉客戶端后更新 html 中的陣列,因為我知道何時點擊Delete Client,html中的陣列保持不變。
我出于好奇問這個問題,我知道這種列印陣列的方式是不正確的,但我想知道是否有任何方法可以更新視圖。
uj5u.com熱心網友回復:
您問題的直接答案是注入ChangeDetectionRef和 呼叫markForCheck。
export class UpdateView {
public client: string[] = ['client 1', 'client 2', 'client 3', 'client 4'];
constructor(private cdr: ChangeDetectionRef) { }
deleteClient() {
this.client.pop();
this.cdr.markForCheck();
}
}
但真正的答案是弄清楚為什么這不更新?您正在執行的編碼型別稱為“可變”編碼。這就是人們在 AngularJS 中編碼的方式。改變物件然后在這些物件上運行變化檢測是 AngularJS 的變化檢測周期如此緩慢的原因。Angular 的變更檢測的作業方式是,如果對物件的參考(在本例中為陣列)是對不同物件的參考,它只會對物件運行變更檢測。由于您正在呼叫pop,因此您指向同一個陣列,因此 Angular 不太可能在其上運行 CD。
以下代碼將為您提供所需的內容并觸發 Angular 的 CD。以下代碼更新this.client為一個新陣列,它將自動獲取 UI 更新。
// THIS IS THE RIGHT ANSWER!!!
this.client = this.client.slice(0, -1);
通過這樣做,您傾向于使用不可變編程,這使得更改檢測更快、更便宜。
uj5u.com熱心網友回復:
嘗試使用 json 管道,并更改<pre>{{ client | json }}</pre>而不是<pre>{{ Client }}</pre>.
<div class="col md:col-6">
<div>
<strong>Client</strong>
<pre>{{ client | json }}</pre>
</div>
<button (click)="deleteClient()">Delete Client</button>
</div>
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/335763.html
標籤:javascript 有角的 角度变化检测
上一篇:在新選項卡中打開按鈕上生成的鏈接
