0
votes

I have implemented a simple table in angular 2 using angular material.

I have implemented a functionality in mat-table where I can select rows from mat-table and after clicking the Transfer Rows ,the selected rows data gets populated outside mat-table in the space provided for the Selected Rows to be displayed.

But as I selected and transfer a row from the mat-table ,the second time also the row is being transferred and I am getting the duplicate rows in the Selected Rows section.

Please access my sample example here..https://stackblitz.com/edit/angular-app-material-h2lcps?file=app%2Faccount%2Faccount.component.ts

Below shown is my output...

enter image description here

Can anybody please tell me how can avoid transferring duplicates....?

1

1 Answers

1
votes

You can check whether a selected element is already present in selectedRows, and only add it if that's not the case.

transferSelectedRows() {
     this.selection.selected.forEach(item => {
      let index: number = this.data.findIndex(d => d === item);
      if(!this.selectedRows.includes(this.data[index])) {
        this.selectedRows.push(this.data[index]);
      }
      console.log(this.data.findIndex(d => d === item));
      console.log(item);

      this.dataSource = new MatTableDataSource<Element>(this.dataSource.data);
    });
    this.selection = new SelectionModel<Element>(true, []);
    this.dataSource.paginator = this.paginator;
  }