'How to remove selected row only from a material table mat-table

How to remove the selected row only in mat-table. Please find the stackblitz link here. https://stackblitz.com/edit/angular-qzh8g4?file=app/table-basic-example.ts

I tried somehow but not working.

remove(val) {
console.log(val);
this.dataSource.splice(this.dataSource.indexOf(val), 1);}


Solution 1:[1]

You could use MatTableDataSource

and set your remove function

remove(element) {
    this.dataSource.data.splice(ELEMENT_DATA.indexOf(element),1);
    this.dataSource = new MatTableDataSource<PeriodicElement>(this.dataSource.data);
}

And online application link

Solution 2:[2]

You will need an immutable operation for that:

this.dataSource = this.dataSource.filter(item => item !== val)

Solution 3:[3]

You have to use renderRows() function of MatTable like below to update your table.

Typescript


displayedColumns: string[] = ['position', 'name', 'weight', 'symbol', 'action'];
  dataSource = ELEMENT_DATA;
  @ViewChild('table') table:MatTable<any>;
  remove(val) {
    console.log(val);
    this.dataSource.splice(this.dataSource.indexOf(val), 1);
    this.table.renderRows();
  }

Html

<!-- table tag -->
<table #table mat-table [dataSource]="dataSource" class="mat-elevation-z8">

....

<!-- remove Column -->
  <ng-container matColumnDef="action">
    <th mat-header-cell *matHeaderCellDef> Action </th>
    <td mat-cell *matCellDef="let element"> <a (click)="remove(element)">Remove</a> </td>
  </ng-container>

Also make sure you are passing column value in remove function instead of event

Solution 4:[4]

Try this:

remove(element) {
    this.dataSource.data = this.dataSource.data.filter(item => item !== element)
    this.dataSource = new MatTableDataSource<IUser>(this.dataSource.data);
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 ahmeticat
Solution 2 Antonis
Solution 3 Vikash Dahiya
Solution 4 Christian Chiama