Reputation: 471
I am using Angular 2 material datatable in one of my projects. There are actually 2 parts to my question:
if I click on any one of the rows in the datatable, I need to get the row index so that I can apply an appropriate CSS on the selected row. I have read the documentation but could not find any mention of getting the index of each row.
I also allow the users to edit individual records in a datatable. For this, each row will have an EDIT button, clicking on which will open a modal dialog pre-populated with values. Once the data has been updated, I want to update the datatable with the new values. I can access the updated data model in the window containing the table. I want to understand how I Can dynamically update a row OR insert a new row in the datatable (the best practices).
Would appreciate any inputs here.
Upvotes: 1
Views: 5273
Reputation: 13
after you dynamically changed the elements in your MatTableDataSource
elements.forEach(ele => { this.dataSource.data.push(ele) });
you can force your table to redraw with
this.dataSource._updateChangeSubscription();
Upvotes: 1
Reputation: 3528
Question #2 really wasn't answered so here is a solution with my delete code but the same for update code. Notice that once the result is a success I call a success modal to notify the user then call a function to remove the row from the data table. This way I don't have to download all the data again.
public deleteMember(memberId) {
// Call the confirm dialog component
this.confirmService.confirm('Confirm Delete', 'This action is final. Gone forever!')
.switchMap(res => {if (res === true) {
return this.appService.deleteItem(this.dbTable, memberId);
}})
.subscribe(
result => {
this.success();
// Refresh DataTable to remove row.
this.updateDataTable (memberId);
},
(err: HttpErrorResponse) => {
console.log(err.error);
console.log(err.message);
this.messagesService.openDialog('Error', 'Delete did not happen.');
}
);
}
Now lets remove, or update, that deleted, or edited, row.
// Remove the deleted row from the data table. Need to remove from the downloaded data first.
private updateDataTable (itemId) {
this.dsData = this.dataSource.data;
if (this.dsData.length > 0) {
for (let i = 0; i < this.dsData.length; i++ ) {
if (this.dsData[i].member_id === itemId) {
this.dataSource.data.splice(i, 1);
}
}
}
this.dataSource.paginator = this.paginator;
}
Upvotes: 0
Reputation: 3715
row.id
html:
<md-row *cdkRowDef="let row; columns: displayedColumns; let index=index;"
(click)="select(row, index)">
</md-row>
ts:
select(row, index) {
// you can use a row id or just a table index
this.selectedRowIndex = row.id;
}
connect()
observable emits a new value. That solution will be specific to your application, but all you need to do is update your data model and then emit your data model again.Upvotes: 2