简体   繁体   English

Angular 11 变更检测问题

[英]Angular 11 change detection issue

I have a situation on my html view where I'm updating the material slider's binding as follows:我在我的 html 视图中有一个情况,我正在更新材质滑块的绑定,如下所示:

 <mat-slider
    [disabled]="isLoading || (isUpdating$ | async)"
    color="primary"
    min="0"
    max="100"
    step="1"
    [ngModel]="myService.thresholdvalue$ | async"
    (change)="maskChanged($event)"
  ></mat-slider>

But when my CHILD COMPONENT calls a service to update it via this.thresholdValueSub.next(value);但是当我的孩子组件通过this.thresholdValueSub.next(value)调用一个服务来更新它时 , I'm getting the classic change detection error: ,我收到了经典的更改检测错误:

ERROR Error: NG0100: ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'undefined'. Current value: '3'

I thought I'd solve it by using async in my view, but I was wrong :我以为我会通过在我看来使用async来解决它,但我错了:

[ngModel]="myService.maskThreshold$ | async"

Then I thought I would run change detection as follows (on my parent component when value is updated):然后我想我会按如下方式运行更改检测(更新值时在我的父组件上):

ngOnInit(): void {

  this.subscriptions
    ...
    .add(this.myService.thresholdValue$.subscribe(res => {
      this.thresholdValue = res;
      if (res !== undefined) {
        this.changeDetector.markForCheck();
      }
    }));
 }

WRONG AGAIN !又错了 ! I'm still getting the Change Detection error.我仍然收到更改检测错误。

Should I post more code to make it clearer ?我应该发布更多代码以使其更清晰吗?

Thank you.谢谢你。

******** UPDATE ********* ********更新********

Remove async pipe from html, since I'm already subbing in the ts file:从 html 中删除异步管道,因为我已经在 ts 文件中添加了字幕:

  <mat-slider
    [disabled]="isLoading || (isUpdating$ | async)"
    color="primary"
    min="0"
    max="100"
    step="1"
    [(ngModel)]="mosaicService.maskThreshold$"
    (change)="maskChanged($event)"
  ></mat-slider>

run change detection when subscribed:订阅时运行更改检测:

.add(this.mosaicService.maskThreshold$.subscribe(res => {
    this.maskValue = res;
    if (res !== undefined) {
      this.changeDetector.detectChanges();
    }
  })

No more change detection errors !不再有变更检测错误! :-) :-)

I ended up removing the async pipe in my HTML, since I was already subscribing in the ts file.我最终删除了 HTML 中的async管道,因为我已经订阅了 ts 文件。 So my mistake was subscribing twice.所以我的错误是订阅了两次。 :-( :-(

Therefore, with this change detector line of code, I'm good to go !因此,使用此更改检测器代码行,我很高兴!

 this.changeDetector.detectChanges();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM