Search code examples
angularcheckboxangular-materialmaterial-table

I want to select in Mat Table with selection Based on dropdown value in angular


I have created a Table with selection using angular material. Now I want to check some particular rows in onchange method of a dropdown. I did so far:

  1. Created the table
  2. Load value in database
  3. Created dropdown and onChange method
  4. Created a save button that gives me the selected value and my dropdown value.

Now I am unable to check the row for the value based on onChange of the dropdown. My dataSource:

const ELEMENT_DATA: PeriodicElement[] = [
  { position: 1, name: 'Hydrogen', weight: 1.0079, symbol: 'H' },
  { position: 2, name: 'Helium', weight: 4.0026, symbol: 'He' },
  { position: 3, name: 'Lithium', weight: 6.941, symbol: 'Li' },
  { position: 4, name: 'Beryllium', weight: 9.0122, symbol: 'Be' },
  
];

In onChange of my dropdown let say I want to check only this two-row

 { position: 1, name: 'Hydrogen', weight: 1.0079, symbol: 'H' },
  { position: 2, name: 'Helium', weight: 4.0026, symbol: 'He' },

Noted:I should be able to check or uncheck after loading value and get a new checked value in my save button Here is my code in stackblitz


Solution

  • you can change your onSelectRole like this

     onSelectRole(e: any) {
        this.selection.clear();
        if(e==1){
          const CheckThisRow = this.dataSource.data.filter(x=>x.position==1)
          this.selection.select(...CheckThisRow);
        }
        if(e==2){
          const CheckThisRow = this.dataSource.data.filter(x=>x.position==4)
           this.selection.select(...CheckThisRow);
        }
      }
    

    NB:pls make changes as you need