Vladlen Gladis
Vladlen Gladis

Reputation: 1787

Can't change Angular2 Material MatChip selected state

How to change MatChip selected property? I wan't on click to select/deselect chip (also it have to change chip color.) What I tried:

html:

<mat-chip-list>
   <mat-chip *ngFor="let label of item.labels" 
             #lbl (click)="selectChip(lbl)">
      {{label}}
   </mat-chip>
</mat-chip-list>

ts:

selectChip(item: MatChip) {
   item.selected ? item.deselect() : item.select();
}

On click it throws

ERROR TypeError: item.select is not a function

How to solve it?

Upvotes: 0

Views: 1311

Answers (2)

gianlucaparadise
gianlucaparadise

Reputation: 1763

If you use this html (please notice #lbl="matChip"):

<mat-chip-list>
   <mat-chip *ngFor="let label of item.labels" 
             #lbl="matChip" (click)="selectChip(lbl)">
      {{label}}
   </mat-chip>
</mat-chip-list>

Your selectChip method will receive a MatChip and then you can do the following:

selectChip(item: MatChip) {
   item.toggleSelected();
}

Upvotes: 2

There isn't a select() or deselect() method, there is just the selected getter and setter functions, so you can solve it like this:

selectChip(item: MatChip) {
   item.selected = !item.selected;
}

Hope this helps.

Upvotes: 0

Related Questions