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 ?
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.
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.
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
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With