Can't change Angular2 Material MatChip selected state

只愿长相守 提交于 2020-01-16 10:09:31

问题


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?


回答1:


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.




回答2:


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();
}


来源:https://stackoverflow.com/questions/47219078/cant-change-angular2-material-matchip-selected-state

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!