Answer the question
In order to leave comments, you need to log in
Angular material table - multiple tables per page, table update after restAPI response, how to do without code duplication?
Hello! Help with code optimization.
There is a view where info is displayed in tables, I use the material for this task.
one table displays information about users, and the other about admins. in the table ID, firstName, lastName, email, etc.
There is a button to update the table, which makes a request to the backend, and pulls out data about users / admins.
The table has checkboxes + filtering. The problem is that I don't like the implementation of the code... each table uses different variables, methods, etc., which aren't really that different.
dataSource = new MatTableDataSource<PeriodicElement>(ELEMENT_DATA);
selection = new SelectionModel<PeriodicElement>(true, []);
dataSourceAdmin = new MatTableDataSource<PeriodicElement>(ELEMENT_DATA_ADMIN);
selectionAdmin = new SelectionModel<PeriodicElement>(true, []);
isAllSelected() {
const numSelected = this.selection.selected.length;
const numRows = this.dataSource.data.length;
return numSelected === numRows;
}
masterToggle() {
this.isAllSelected() ?
this.selection.clear() :
this.dataSource.data.forEach(row => this.selection.select(row));
}
checkboxLabel(row?: PeriodicElement): string {
if (!row) {
return `${this.isAllSelected() ? 'select' : 'deselect'} all`;
}
return `${this.selection.isSelected(row) ? 'deselect' : 'select'} row ${row.position + 1}`;
}
isAllSelectedForAdmin() {
const numSelected = this.selectionAdmin.selected.length;
const numRows = this.dataSourceAdmin.data.length;
return numSelected === numRows;
}
masterToggleForAdmin() {
this.isAllSelected() ?
this.selectionAdmin.clear() :
this.dataSourceAdmin.data.forEach(row => this.selectionAdmin.select(row));
}
checkboxLabelForAdmin(row?: PeriodicElement): string {
if (!row) {
return `${this.isAllSelectedForAdmin() ? 'select' : 'deselect'} all`;
}
return `${this.selectionAdmin.isSelected(row) ? 'deselect' : 'select'} row ${row.position + 1}`;
}
dataSource = new MatTableDataSource<PeriodicElement>(NEW DATA FROM RESPONSE);
selection = new SelectionModel<PeriodicElement>(true, []);
Answer the question
In order to leave comments, you need to log in
To avoid code duplication, you can change the functions to receive objects of a specific table as arguments in them, in which case one function can be used for both tables
isAllSelected(selection, dataSource) {
const numSelected = selection.selected.length;
const numRows = dataSource.data.length;
return numSelected === numRows;
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question