tprieboj
tprieboj

Reputation: 1703

Angular material 2 preselect mat-table rows

I am trying to preselect rows with angular material table. There is initialSelection in SelectionModel see example. But there is no exact explanation how it works. Is it possible to use this initialSelection to make some rows preselected?


Edit 1:

It looks like, that initialSelection needs to be subset of data array passed as dataSource to mat-table. It is working now.

Edit 2:

Updated offical example. Look at app/table-selection-example.ts lines 21 - 25

  subSet1 = this.dataSource.data.slice(0,2);
  subSet2 = this.dataSource.data.slice(3,5);
  preselectExample = this.subSet1.concat(this.subSet2);

  selection = new SelectionModel<Element>(true, this.preselectExample);

Upvotes: 2

Views: 1840

Answers (1)

Nerijus Pamedytis
Nerijus Pamedytis

Reputation: 134

So, after a long battle with table and lots of selections I did it a bit better than slicing and dicing the array.

this.initialSelection = this.data.filter((element,e) => {
     return this.savedSelection.some( (val,i) => { 
         if(element.key === val.key) { 
             this.data[e]['amount'] = val['amount']; 
             return true;
         }
     return;
  });
});
this.dataSource.data = this.data;
this.selection = new SelectionModel<any>(true, this.initialSelection);

there's also an extra for editable values and later asign values back to the table for the ones that are selected.

Cheers.

https://stackblitz.com/edit/angular-urd5c4

Upvotes: 1

Related Questions