Search code examples
angularselectforeachinotifypropertychangedchecked

Changed after checked - Angular [selected]


I'm using material chips for tags in Angular, which are looped by *ngFor.

<mat-chip class="c-pointer" *ngFor="let popularTag of popularTags; let i=index" [selected]="popularTag.is_user_tag" (click)="toggleTag(i)">#{{ popularTag.title }}</mat-chip>

I need, to toggle 'is_user_tag' value on chip click, but it throws the error

ERROR Error: ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'mat-chip-selected: true'. Current value: 'mat-chip-selected: false'

I tried setTimeout() and ChangeDetectorRef methods, but none of them solved the problem.

How can I fix this problem?


Solution

  • The problem occurs when you have more than one selected chip. If you want multiselect, you have to set [multiple]="true" on mat-chip-list

    <mat-chip-list [multiple]="true">
        <mat-chip class="c-pointer" *ngFor="let popularTag of popularTags; let i=index" [selected]="popularTag.is_user_tag" (click)="toggleTag(i)">#{{ popularTag.title }}</mat-chip>
    </mat-chip-list>
    

    Demo: https://stackblitz.com/edit/angular-x7tkwc