Angular 11 change detection issue

524 Views Asked by At

I have a situation on my html view where I'm updating the material slider's binding as follows:

 <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);, 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 :

[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:

  <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 ! :-)

1

There are 1 best solutions below

0
On BEST ANSWER

I ended up removing the async pipe in my HTML, since I was already subscribing in the ts file. So my mistake was subscribing twice. :-(

Therefore, with this change detector line of code, I'm good to go !

 this.changeDetector.detectChanges();