Angular Mat Select Multiple selectionchange finding which option was changed

前提是你 提交于 2019-11-27 03:13:35

问题


I have a <mat select> with the multiple option set (a multi-select). When the selectionChange event fires I need to know which option has been checked or unchecked, however, it only returns the new current list of selected options.

For instance I have a list:

<mat-select (selectionChange)="change($event)" multiple placeholder="Select">
  <mat-option value="1">one</mat-option>
  <mat-option value="2">two</mat-option>
  <mat-option value="3">three</mat-option>
  <mat-option value="4">four</mat-option>
</mat-select>

If options one, three and four are checked and then the user unchecked option four, in the event handler I need to know which option triggered the event (i.e. option four) and its new state. I currently don't see a way of accessing that information in the selectionChange event.

https://stackblitz.com/edit/angular-1e9gsd?file=app/select-overview-example.ts

I tried putting the event handler (selectionChange)="change($event)" on the <mat-option> but it doesn't seem to be supported.


回答1:


I needed to use onSelectionChange on the <mat-option>, which is different than the selectionChange that you can use on the <mat-select>

It would be nice if that was in the documentation for mat-select.

Here it is working https://stackblitz.com/edit/angular-1e9gsd-34hrwg?file=app/select-overview-example.html




回答2:


This worked for me. blahs is an array of strings in this case. Use 2-way binding:

<mat-select placeholder="choose..." [(value)]="selected" 
      (selectionChange)="somethingChanged(selected)">
  <mat-option *ngFor="let b of blahs; index as i;" value={{b[i]}}">{{b[i]}}
  </mat-option>
</mat-select>


来源:https://stackoverflow.com/questions/50614991/angular-mat-select-multiple-selectionchange-finding-which-option-was-changed

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