Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Current selected value in angular6 material mat-selection-list

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

like image 859
Anil Arya Avatar asked Jun 01 '18 05:06

Anil Arya


2 Answers

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

like image 145
Roel Avatar answered Oct 02 '22 16:10

Roel


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);
}
like image 32
Prachi Avatar answered Oct 02 '22 17:10

Prachi