Search code examples
angularangular-materialangular5angular-material2angular-material-5

Inbuilt deselectAll method not working in multiple Angular mat-selection-list


I am using angular5 to create multiple mat-selection-list in same component.

list-selection-example.html

 Shoes: 
<mat-selection-list #shoes>
  <mat-list-option *ngFor="let shoe of typesOfShoes" 
                   [value]="shoe">
    {{shoe}}
  </mat-list-option>
</mat-selection-list>

<button mat-button  (click)="deselectShoes()">Deselect all Shoes</button>

Cloths: 
<mat-selection-list #cloths>
  <mat-list-option *ngFor="let cloth of typesOfCloths" 
                   [value]="cloth">
    {{cloth}}
  </mat-list-option>
</mat-selection-list>

<button mat-button  (click)="deselectCloth()">Deselect all Cloths</button>

list-selection-example.ts

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

  typesOfCloths = ['Amaxa', 'Cotton', 'Woolen', 'Nylon'];

    @ViewChild(MatSelectionList) shoes: MatSelectionList;
    @ViewChild(MatSelectionList) cloths: MatSelectionList;


  deselectShoes(){
    this.shoes.deselectAll(); 
  }

  deselectCloth(){
    this.cloths.deselectAll(); 
  }
  ngOnInit(){

  }
}

Here is complete code : https://stackblitz.com/edit/angular-i3pfu2-dla3rd?file=app%2Flist-selection-example.ts

In this example, deselectShoes() method is working as expected. But deselectCloth() is not working as expected , its deselecting shoes only.

How we can fix this ?


Solution

  • You are misunderstanding how the decorator @ViewChild works and in both variables you are selecting the same element. It should be something like this:

    @ViewChild('shoes') shoes: MatSelectionList;
    @ViewChild('cloths') cloths: MatSelectionList;
    

    You can read more about it here.