Angular2使用单向数据绑定更新视图

时间:2018-10-29 21:31:54

标签: angular angular-material

如果我正确理解,则从模型到视图都是单向数据绑定,它是使用双花括号{{}}或方括号[]实现的。

我想更新按钮内的计数器(徽章)。在模型更改后,更新不会自动反映出来,而是在单击按钮后更新。一切都在同一组件中完成。

我的代码:

.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>

我想念什么吗?谢谢。

2 个答案:

答案 0 :(得分:1)

似乎获得新计数器的功能不在ngZone变化检测范围内。您可以使用setTimeout进行尝试。特别是在涉及第三方的情况下。

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

答案 1 :(得分:0)

我找到了解决问题的方法,当在Leaflet事件处理程序中进行更改时,您需要触发更改检测,这是因为Leaflet回调在Angular区域之外运行。因此,我要做的是将Angular区域引用注入,然后在函数处理程序中注入:

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

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

相关问题