首页 > 解决方案 > angular6 材质 mat-selection-list 中的当前选定值

问题描述

使用 Angular Material2 mat-selection-list,能够识别当前选项是选中还是未选中[Boolean]。

组件.html

<mat-selection-list #shoes (selectionChange)="onSelection($event, shoes.selectedOptions)" >
  <mat-list-option *ngFor="let shoe of typesOfShoes" [value]='shoe'>
    {{shoe}}
  </mat-list-option>
</mat-selection-list>

组件.ts

export class ListSelectionExample {
  typesOfShoes = ['Boots', 'Clogs', 'Loafers', 'Moccasins', 'Sneakers'];

  onSelection(e, v){
   console.error(e.option.selected,v); 
  }
}

e.option.selected通知当前选项是选中还是未选中。

如何识别当前选择的值?尝试了ngModel 和 ngModelChange的多种组合并单击,对我没有任何作用。

https://stackblitz.com/edit/angular-eyjdfp-qgjhvd?file=app%2Flist-selection-example.ts

标签: angularangular-materialangular-material2angular6

解决方案


You can get current selected value by getting e.option.value of your selectionChange $event

component.ts

current_selected: string;

onSelection(e, v){
   this.current_selected = e.option.value;
}

component.html

<p>
  Current selected value: {{ current_selected }}
</p>

Bonus

You can list all selected items by calling property selected of shoes.selectedOptions.selected in the template.

component.html

<p>Selected:</p>
<ul>
  <li *ngFor="let i of shoes.selectedOptions.selected">
    {{ i.value }}
  </li>
</ul>

Working Demo


推荐阅读