Search code examples
angularangular-changedetection

ERROR Error: ExpressionChangedAfterItHasBeenCheckedError:


I have a good intuition why this error is happening here:

https://stackblitz.com/edit/angular-qjajn1?file=.angular-cli.json

<mat-button-toggle-group multiple #t="matButtonToggleGroup" (change)="d($event)">
    <mat-button-toggle checked *ngFor="let f of features" [value]=f>{{f}}</mat-button-toggle>
</mat-button-toggle-group>

<mat-checkbox
    [checked]="t.value.length == features.length"
    [indeterminate]="t.value.length && !(t.value.length == features.length)"
    (change)="$event.checked ? t.value = features : t.value = [];"
    color="primary"
> all </mat-checkbox>

Im changing stuff in the template "after view initialization". Is there a TEMPLATE DRIVEN solution to get rid of this error ?

I know how I can resolve this issue by adding code to my *.TS file. Calling change detection in AfterViewInit etc, or using reactive form model on the checkbox and setting the value to true.

Is there a way I can solve this entirely in the template?

  • Well its works anyways and in production I wont get that error.

Solution

  • Using components parameters instead of template reference avoid this error :

    Add the value to the component :

     value = this.features;
    

    Template :

    <mat-button-toggle-group multiple (change)="d($event)" [(ngModel)]="value">
        <mat-button-toggle checked *ngFor="let f of features" [value]=f>
         {{f}}
        </mat-button-toggle>
    </mat-button-toggle-group>
    
    <mat-checkbox 
    [checked]="value?.length === features.length" 
    [indeterminate]="value.length && !(value.length === features.length)"
     (change)="$event.checked ? value = features : value = []" 
     color="primary">
      all 
    </mat-checkbox>
    

    Running example