Working with Angular Material2 mat-selection-list, Able to identify whether current option is selected or non-selected[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
notifies whether current option is selected or non-selected.
How to identify current selected value ? Tried with multiple combinations with ngModel and ngModelChange and click , nothing works for me.
https://stackblitz.com/edit/angular-eyjdfp-qgjhvd?file=app%2Flist-selection-example.ts
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
Use the click
event binding on the mat-list-option
:
<mat-selection-list #shoes (selectionChange)="onSelection($event, shoes.selectedOptions)" >
<mat-list-option *ngFor="let shoe of typesOfShoes" [value]='shoe' (click)="getValue($event)">
{{shoe}}
</mat-list-option>
</mat-selection-list>
Component TypeScript:
getValue(event){
console.log(event.target.parentNode.innerText);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With