1

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

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

我的代码:

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

我错过了什么吗?谢谢你。

4

2 回答 2

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
}
于 2018-10-30T03:34:23.150 回答
0

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

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

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

于 2018-10-30T10:43:22.800 回答