Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular Material Table | Add Remove rows at runtime

I am using Angular Material Table that is backed by a plain array as the data source.

this.employees = this.route.snapshot.data.employes; // of type Employee[] resolved using a Resolve guard
this.dataSource = new MatTableDataSource<Employee>(this.employees);

Once rendered initially, I want to add/remove rows from the data table by modifying the 'this.employess' array using method in my component :-

addEmployee(e: Employee){
 this.employess.push(e);   // I expect the table to have one row added after this.
}

removeEmployee(index : number){
  // splice the array at given index & remove one row from data table
}

PROBLEM

The data table rows are not affected when I add remove elements in my array. I found an a blog elaborating same problem but uses a custom data source. Is there any way using plain array ?

like image 706
Kumar Sambhav Avatar asked Mar 08 '18 12:03

Kumar Sambhav


People also ask

How do you delete a row in a table in angular?

Using the ng-repeat directive, we bind data to our HTML table. Now on the delete button, we added directive ng-click, and with deleteRow() function, the selected row gets deleted.

What is MatTableDataSource?

MatTableDataSource. Data source that accepts a client-side data array and includes native support of filtering, sorting (using MatSort), and pagination (using MatPaginator). Allows for sort customization by overriding sortingDataAccessor, which defines how data properties are accessed.


2 Answers

The Simplest way is to call _updateChangeSubscription() on your dataSource as you are already using MatTableDataSource

this.dataSource = new MatTableDataSource(this.employees);

Your new modified addEmployee method will become:

addEmployee(e: Employee){
 this.employess.push(e);   // I expect the table to have one row added after this.
 this.dataSource._updateChangeSubscription()  // THIS WILL DO
}
like image 187
Arun Sharma Avatar answered Nov 15 '22 10:11

Arun Sharma


In Latest versions of Angular Material 7/8

You need to call .renderRows() method after pushing new row data

addRowData(row_obj){
   var d = new Date();
   this.dataSource.push({
     id:d.getTime(),
     name:row_obj.name
   });
   this.table.renderRows();
 }

 deleteRowData(row_obj){
    this.dataSource = this.dataSource.filter((value,key)=>{
      return value.id != row_obj.id;
    });
 }

Source Tutorial link

enter image description here

like image 22
Code Spy Avatar answered Nov 15 '22 10:11

Code Spy