使用Angular Material2 mat-selection-list ,能够识别当前选项是选中还是未选中[Boolean]。
compnenent.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>
component.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
最佳答案
您可以通过获取所选的e.option.value
来获取当前选定的值更改$event
component.ts
current_selected: string;
onSelection(e, v){
this.current_selected = e.option.value;
}
component.html
<p>
Current selected value: {{ current_selected }}
</p>
奖励
您可以通过调用模板中
shoes.selectedOptions.selected
的选定属性来列出所有选定项。component.html
<p>Selected:</p>
<ul>
<li *ngFor="let i of shoes.selectedOptions.selected">
{{ i.value }}
</li>
</ul>
Working Demo