【发布时间】:2021-07-22 02:41:45
【问题描述】:
我的 html 视图中有一种情况,我正在更新材质滑块的绑定,如下所示:
<mat-slider
[disabled]="isLoading || (isUpdating$ | async)"
color="primary"
min="0"
max="100"
step="1"
[ngModel]="myService.thresholdvalue$ | async"
(change)="maskChanged($event)"
></mat-slider>
但是当我的 CHILD COMPONENT 通过 this.thresholdValueSub.next(value); 调用服务来更新它时,我得到了经典的更改检测错误:
ERROR Error: NG0100: ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'undefined'. Current value: '3'
我认为我可以通过使用async 来解决它,但我错了:
[ngModel]="myService.maskThreshold$ | async"
然后我想我会按如下方式运行更改检测(在更新值时在我的父组件上):
ngOnInit(): void {
this.subscriptions
...
.add(this.myService.thresholdValue$.subscribe(res => {
this.thresholdValue = res;
if (res !== undefined) {
this.changeDetector.markForCheck();
}
}));
}
又错了!我仍然收到更改检测错误。
我应该发布更多代码以使其更清晰吗?
谢谢。
******** 更新 *********
从 html 中删除异步管道,因为我已经在 ts 文件中进行了替换:
<mat-slider
[disabled]="isLoading || (isUpdating$ | async)"
color="primary"
min="0"
max="100"
step="1"
[(ngModel)]="mosaicService.maskThreshold$"
(change)="maskChanged($event)"
></mat-slider>
订阅时运行更改检测:
.add(this.mosaicService.maskThreshold$.subscribe(res => {
this.maskValue = res;
if (res !== undefined) {
this.changeDetector.detectChanges();
}
})
不再有变更检测错误! :-)
【问题讨论】:
-
你能创建 stackblitz 吗?
-
这个场景有点复杂,所以我在考虑如何把它分解成一个小的SB项目。谢谢。
标签: angular angular2-changedetection change-detector-ref