Can't change Angular2 Material MatChip selecte

2019-08-26 01:25发布

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?

2条回答
疯言疯语
2楼-- · 2019-08-26 02:04

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.

查看更多
Juvenile、少年°
3楼-- · 2019-08-26 02:05

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();
}
查看更多
登录 后发表回答