问题
I have a material Table with expandable rows (https://material.angular.io/components/table/examples) and I want to manage delete into the table itself, so I create a delete button with a function that trigger the delete event. The api works, the record is correctly deleted, but the table is not refreshed after delete, and I want to implement this behaviour. Here a stackblitz with fake api: https://stackblitz.com/edit/angular-comzph
I try, in my delete function to call ngOnInt and to navigate back to the same route, but nothing happens...
deleteCustomer(id) {
this.api.deleteCustomer(id)
.subscribe(res => {
alert(`cliente rimosso`);
// TODO fix reload list after delete
// this.router.navigate['/clienti'];
this.ngOnInit();
}, (err) => {
console.log(err);
}
);
}
I try to use this solution too, but does not works. I try using ngOnChange and ngOnDestroy, but does not works too...
Could someone help me?
回答1:
There is no need to call the server for the updated data and download all the data again. Just call this function (below) and delete the row (splice) in the dataSource. Pass in the record id from your delete function and whatever the column name is where your id's are and magic happens. I include the paginator.
My StackBlitz for Angular Material Table has a working example. Also see my UpdateDatatableService which I use for CREATE AND UPDATE.
// Remove the deleted row from the data table.
// Need to remove from the downloaded data first.
private deleteRowDataTable (recordId, idColumn, paginator, dataSource) {
this.dsData = dataSource.data;
const itemIndex = this.dsData.findIndex(obj => obj[idColumn] === recordId);
dataSource.data.splice(itemIndex, 1);
dataSource.paginator = paginator;
}
回答2:
I solved creating a new datasource for mat-table every time the customer list is refreshed. I need to provide ChangeDetectorRef
to my constructor, then to write this code:
refreshCustomersList() {
this.api.getCustomers()
.subscribe(res => {
console.log(res);
this.clienti = res;
this.dataSource = new ClientiDataSource(this.api);
this.changeDetectorRefs.detectChanges();
}, err => {
console.log(err);
});
}
And it works!
NB: This is a problem only if you are using mat-table datasource
来源:https://stackoverflow.com/questions/51280234/angular-refresh-table-after-delete-record-using-material-table-and-rest-api