Angular Material Table with SelectionModel and Pagination: A Comprehensive Guide
Mastering Angular Material: A Comprehensive Guide to Tables, Selections, and Pagination
Introduction
Angular Material is a powerful UI framework for building web applications with Angular. One of its key components is the MatTableModule, which provides a feature-rich data table. In this article, we’ll explore how to use Angular Material’s MatTable along with SelectionModel for handling row selection, and we’ll integrate pagination for better user experience.
Setting Up Angular Material
Before diving into the code, make sure you have an Angular project set up. If not, you can create one using Angular CLI:
ng new my-angular-material-app
cd my-angular-material-app
ng add @angular/material
Follow the prompts to set up Angular Material in your project.
Creating the Angular Material Table
Now, let’s create a basic Angular Material table with a SelectionModel.
Open the app.module.ts
file and import the necessary Angular Material modules:
import { MatTableModule } from '@angular/material/table';
import { MatCheckboxModule } from '@angular/material/checkbox';
Include these modules in the imports
array of @NgModule
:
@NgModule({
declarations: [
// ... your components
],
imports: [
MatTableModule,
MatCheckboxModule,
// ... other modules
],
bootstrap: [AppComponent],
})
export class AppModule {}
Now, in your component file (app.component.ts
), define a simple datasource and columns for the table:
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
template: `
<mat-table [dataSource]="dataSource" matSort>
<!-- Your columns go here -->
</mat-table>
`,
styleUrls: ['./app.component.css'],
})
export class AppComponent {
// Define your data source
dataSource = [
{ id: 1, name: 'Item 1' },
{ id: 2, name: 'Item 2' },
// ... more data
];
// Define your columns
}
Now, let’s add the SelectionModel to enable row selection. Update your component file:
import { SelectionModel } from '@angular/cdk/collections';
// ...
export class AppComponent {
// Define your selection model
selection = new SelectionModel<any>(true, []);
// ...
// Add a column for checkboxes
columns: string[] = ['select', 'id', 'name'];
}
Update the template to include the checkboxes in the first column:
<mat-table [dataSource]="dataSource" matSort>
<!-- Checkbox column -->
<ng-container matColumnDef="select">
<mat-header-cell *matHeaderCellDef>
<mat-checkbox (change)="$event ? masterToggle() : null" [checked]="selection.hasValue() && isAllSelected()">
</mat-checkbox>
</mat-header-cell>
<mat-cell *matCellDef="let row">
<mat-checkbox (click)="$event.stopPropagation()" (change)="$event ? selection.toggle(row) : null" [checked]="selection.isSelected(row)">
</mat-checkbox>
</mat-cell>
</ng-container>
<!-- Other columns -->
<ng-container matColumnDef="id">
<mat-header-cell *matHeaderCellDef mat-sort-header> ID </mat-header-cell>
<mat-cell *matCellDef="let row"> {{ row.id }} </mat-cell>
</ng-container>
<ng-container matColumnDef="name">
<mat-header-cell *matHeaderCellDef mat-sort-header> Name </mat-header-cell>
<mat-cell *matCellDef="let row"> {{ row.name }} </mat-cell>
</ng-container>
<!-- Add other columns as needed -->
<mat-header-row *matHeaderRowDef="columns"></mat-header-row>
<mat-row *matRowDef="let row; columns: columns;"></mat-row>
</mat-table>
Implement the helper functions in your component:
// ...
export class AppComponent {
// ...
// Check if all rows are selected
isAllSelected() {
const numSelected = this.selection.selected.length;
const numRows = this.dataSource.length;
return numSelected === numRows;
}
// Select or deselect all rows
masterToggle() {
this.isAllSelected() ? this.selection.clear() : this.dataSource.forEach((row) => this.selection.select(row));
}
}
Now, you have a basic Angular Material table with a SelectionModel. Next, let’s add pagination to enhance the usability.
Adding Pagination
Import the MatPaginator module in app.module.ts
:
import { MatPaginatorModule } from '@angular/material/paginator';
Include it in the imports
array of @NgModule
:
@NgModule({
declarations: [
// ... your components
],
imports: [
MatTableModule,
MatCheckboxModule,
MatPaginatorModule, // Add MatPaginatorModule here
// ... other modules
],
bootstrap: [AppComponent],
})
export class AppModule {}
Update your component file to include pagination:
import { MatPaginator } from '@angular/material/paginator';
// ...
export class AppComponent {
// ...
// Include MatPaginator
@ViewChild(MatPaginator) paginator: MatPaginator;
// ...
// Set up the paginator
ngAfterViewInit() {
this.dataSource.paginator = this.paginator;
}
}
Update your template to include the paginator:
<!-- Add this below your mat-table -->
<mat-paginator [pageSizeOptions]="[5, 10, 25, 100]" showFirstLastButtons></mat-paginator>
Now, your Angular Material table includes a SelectionModel, and pagination is integrated for better navigation through the data.
Stackblitz link: Click Here
FAQ
Q: How can I customize the appearance of the checkboxes?
You can customize the appearance of checkboxes by applying your own styles. You can use the ::ng-deep
selector to target the checkbox elements within the component. For example:
::ng-deep .mat-checkbox-inner-container {
background-color: #2196f3; /* Change background color */
border-color: #2196f3; /* Change border color */
}
Q: Can I use a different data source for the table?
Yes, you can use any data source that matches the structure expected by the MatTable. Make sure to update the displayed columns accordingly.
Q: How do I handle actions when a row is selected?
You can subscribe to the selection.changed
event to get notified when the selection changes. For example:
this.selection.changed.subscribe((selected) => {
console.log('Selected rows:', selected);
// Add your custom logic here
});
Conclusion
In this article, we explored how to create an Angular Material table with SelectionModel and pagination. This combination provides a user-friendly way to interact with large sets of data while allowing users to select and perform actions on specific rows. Feel free to customize the code to suit your application’s specific needs.
Remember to check the Angular Material documentation for more details and options available for MatTable, SelectionModel, and MatPaginator.
Happy coding!