13

How do I get the list of all values selected from Angular material mat selection list in the component. The example given shows values to be displayed in the template but not in component. I am trying to modify the solution given in this question but its not working for me. Here is my current code:

Template:

<mat-selection-list #selected [(ngModel)]="readingTypesSelected" (ngModelChange)="onSelection($event)" >
  <mat-list-option *ngFor="let readingType of readingTypes">
    {{readingType.name}}
  </mat-list-option>
</mat-selection-list>

Component:

    onSelection(e, v) {

    console.log(e);
    console.log(v);    
  }

The following is getting logged to console:

enter image description here

How do i extract actual values of selected options from this?

Solution:

The first two lines of template code should be (as given in stackblitz link in accepted solution):

<mat-selection-list #selected (selectionChange)="onSelection($event, selected.selectedOptions.selected)" >
      <mat-list-option *ngFor="let readingType of readingTypes" [value] ="readingType">
Abhay Kumar
  • 833
  • 3
  • 11
  • 24

5 Answers5

11

Try this

<mat-selection-list #list [(ngModel)]="selectedOptions" (ngModelChange)="onNgModelChange($event)">
    <mat-list-option *ngFor="let shoe of typesOfShoes" [value]="shoe">
      {{shoe}}
    </mat-list-option>
</mat-selection-list>

After binding [(ngModel)]="selectedOptions" you can use selectedOptions variable in your component which will have all selected items.

Example:https://stackblitz.com/edit/angular-hdmfwi

Aray Karjauv
  • 2,679
  • 2
  • 26
  • 44
Chellappan வ
  • 23,645
  • 3
  • 29
  • 60
2

This solution is better

selectionChanged(event: MatSelectionListChange): void {
    this.selected = event.options.filter(o => o.selected).map(o => o.value);
}
Rafik Belkadi
  • 146
  • 1
  • 6
1

In your code value attribute is missing

Replace:

<mat-list-option *ngFor="let readingType of readingTypes">

with:

<mat-list-option *ngFor="let readingType of readingTypes" [value]="readingType">

and then get the selected array in readingTypesSelected,

readingTypesSelected is mentioned in [(ngModel)]="readingTypesSelected"

Duck Ling
  • 1,577
  • 13
  • 20
Imran Muhammad
  • 556
  • 5
  • 7
1
<mat-selection-list #products [(ngModel)]="selectedProducts">
    <mat-list-option *ngFor="let eachProduct of allProducts;" [value]="eachProduct">
        {{eachProduct.name}}
    </mat-list-option>
</mat-selection-list>

{{selectedProducts|json}}

Tested in Angular 10. The main part is [value]="eachProduct" other wise it will show null

Pranoy Sarkar
  • 1,965
  • 14
  • 31
0

I updated your stackblitz code here https://angular-selection.stackblitz.io

Now you can get selected values in console.

Chintan Kukadiya
  • 784
  • 5
  • 16