簡體   English   中英

Angular2使用單向數據綁定更新視圖

[英]Angular2 Updating view using one-way data binding

如果我理解正確,則單向數據綁定是從模型到視圖的,並且是使用雙花括號{{}}或方括號[]實現的。

我想更新按鈕內的計數器(徽章)。 在模型更改后,更新不會自動反映出來,而是在單擊按鈕后更新。 一切都在同一組件中完成。

我的代碼:

html的:

<button
mat-raised-button
matStepperNext
[matBadge]="polygonCounter"
matBadgePosition="below"
matBadgeColor="accent">
Next
</button>

.TS:

polygonCounter: number; //declared

 ngOnInit() {
...
    this.polygonCounter = 0;
...
  }

更改值的函數:

onMapDrawed(e): void {
    ....
    this.polygonCounter = 0;
    let counter = 0;
    ...//function that get the new counter
    this.polygonCounter = counter; //counter has the new value
}

這也不會在視圖中更新,例如:

<p>{{polygonCounter}}</p>

我想念什么嗎? 謝謝。

看起來獲得新計數器的功能不在ngZone變化檢測范圍之內。 您可以使用setTimeout嘗試一下。 特別是在涉及第三方的情況下。

onMapDrawed(e): void {
    ....
    this.polygonCounter = 0;
    let counter = 0;
    ...//function that get the new counter
    setTimeout(()=>this.polygonCounter = counter); //change in setTimeout
}

我發現了問題的解決方案,當在Leaflet事件處理程序中進行更改時,您需要觸發更改檢測,這是因為Leaflet回調在Angular區域之外運行。 所以我要做的是注入Angular區域引用,然后注入我的函數處理程序中:

this.zone.run(() => {
  this.polygonCounter = counter;
});

如此處所示: https : //github.com/Asymmetrik/ngx-leaflet/issues/118

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM