This user interface component offers an intuitive way to manage large datasets. It provides pagination, filtering, and sorting options, allowing users to efficiently navigate, refine, and organize data according to their needs

Here is a complete working example of an Angular Material Data Table with pagination, sorting and filtering.

Implementing Angular Material table with pagination, filtering and sorting

Angular material is a Google user interface library that is used by the google developers across all the Google products. Angular material focus on the minimal design with high performance.

It provide variety of control, here we are focusing on the material table only.

Importing Data Table Modules

First you need to import BrowserAnimationsModule. BrowserAnimationsModule is the dependent module to run other material modules. Below 3 modules for the data table which is mandatory to import.

1- MatTableModule for the mat data table
2 – MatSortModule for the sorting elements by clicking on the header
3 – MatPaginatorModule for the pagination show page size, next and page size dropdown

Other modules are MatButtonModule, MatIconModule, MatTooltipModule and others are used to construct a template for the button, icons, and tooltips. these are also you can import for better look and feel. I have added almost all the modules, but you can avoid to add if not required.

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { HttpClientModule } from '@angular/common/http';
import { RouterModule, Routes } from '@angular/router';

import { AppComponent } from './app.component';
import { MaterialtableComponent } from './materialtable/materialtable.component';

import { MatTableModule } from '@angular/material/table';
import { MatPaginatorModule } from '@angular/material/paginator';
import { MatSortModule } from '@angular/material/sort';
import {MatIconModule} from '@angular/material/icon';
import {DragDropModule} from '@angular/cdk/drag-drop';
import {CommonModule} from '@angular/common';
import { A11yModule } from '@angular/cdk/a11y';
import { CdkTableModule } from '@angular/cdk/table';
import { ScrollingModule } from '@angular/cdk/scrolling';
import { MatTooltipModule } from '@angular/material/tooltip';
import { CdkTreeModule } from '@angular/cdk/tree';
import { MatAutocompleteModule } from '@angular/material/autocomplete';
import {MatBadgeModule} from '@angular/material/badge';
import {MatBottomSheetModule} from '@angular/material/bottom-sheet';
import {MatButtonModule} from '@angular/material/button';
import {MatButtonToggleModule} from '@angular/material/button-toggle';
import {MatCardModule} from '@angular/material/card';
import {MatCheckboxModule} from '@angular/material/checkbox';
import {MatChipsModule} from '@angular/material/chips';
import { MatStepperModule } from '@angular/material/stepper';
import {MatDatepickerModule} from '@angular/material/datepicker';
import {MatDialogModule} from '@angular/material/dialog';
import {MatDividerModule} from '@angular/material/divider';
import {MatExpansionModule} from '@angular/material/expansion';
import {MatGridListModule} from '@angular/material/grid-list';
import {MatInputModule} from '@angular/material/input';
import { MatListModule } from '@angular/material/list';
import { MatMenuModule } from '@angular/material/menu';
import { MatNativeDateModule, MatRippleModule } from '@angular/material/core';
import { MatProgressBarModule } from '@angular/material/progress-bar';
import { MatProgressSpinnerModule } from '@angular/material/progress-spinner';
import { MatRadioModule } from '@angular/material/radio';
import { MatSelectModule } from '@angular/material/select';
import { MatSidenavModule } from '@angular/material/sidenav';
import { MatSliderModule } from '@angular/material/slider';
import { MatSlideToggleModule } from '@angular/material/slide-toggle';
import { MatSnackBarModule } from '@angular/material/snack-bar';
import { MatTabsModule } from '@angular/material/tabs';
import { MatToolbarModule } from '@angular/material/toolbar';
import { MatTreeModule } from '@angular/material/tree';
   
const appRoutes: Routes = [
  { path: '', pathMatch: 'full', redirectTo: 'home' },
  { path: 'home', component: MaterialtableComponent },
];

@NgModule({
  declarations: [AppComponent, MaterialtableComponent],
  imports: [
    BrowserModule,
    FormsModule,
    ReactiveFormsModule,
    HttpClientModule,
    RouterModule.forRoot(
      appRoutes
      //{ enableTracing: true } // <-- debugging purposes only
    ),
    BrowserAnimationsModule,
    MatTableModule,
    MatSortModule,
    MatPaginatorModule,
    MatIconModule,
    DragDropModule,
    CommonModule,
    A11yModule,
    CdkTableModule,
    CdkTreeModule,
    MatAutocompleteModule,
    MatBadgeModule,
    MatBottomSheetModule,
    MatButtonModule,
    MatButtonToggleModule,
    MatCardModule,
    MatCheckboxModule,
    MatChipsModule,
    MatStepperModule,
    MatDatepickerModule,
    MatDialogModule,
    MatDividerModule,
    MatExpansionModule,
    MatGridListModule,
    MatInputModule,
    MatListModule,
    MatMenuModule,
    MatNativeDateModule,
    MatProgressBarModule,
    MatProgressSpinnerModule,
    MatRadioModule,
    MatRippleModule,
    MatSelectModule,
    MatSidenavModule,
    MatSliderModule,
    MatSlideToggleModule,
    MatSnackBarModule,
    MatTabsModule,
    MatToolbarModule,
    MatTooltipModule,
    MatTreeModule,
    ScrollingModule,
  ],
  providers: [],
  exports: [RouterModule],
  bootstrap: [AppComponent],
  schemas: [CUSTOM_ELEMENTS_SCHEMA]
})
export class AppModule {}

Note Before version 9 & on or after 9 version the import are change like

@angular/material/<module> you need to import individual module in version 9

@angular/material Previous version < 9 you can import all in once.

Create component

ng g component materialtable –skipTests

It will create 3 files .ts, .html and .css file.

1- materialtable.component.ts

import { Component, ViewChild } from '@angular/core';
import { MatPaginator } from '@angular/material/paginator';
import { MatTableDataSource } from '@angular/material/table';
import { MatSort } from '@angular/material/sort';

export interface IHeaders {
  id: string | number;
  name: string;
  age: number | string;
  gender: string;
  country: string;
}

@Component({
  selector: 'app-materialtable',
  templateUrl: './materialtable.component.html',
  styleUrls: ['./materialtable.component.css']
})
export class MaterialtableComponent {
  displayedColumns = ['id', 'name', 'age', 'gender', 'country'];
  dataSource: MatTableDataSource<IHeaders>;

  @ViewChild(MatPaginator) paginator: MatPaginator;
  @ViewChild(MatSort) sort: MatSort;

  constructor() {
    const users: IHeaders[] = [];
    for (let i = 1; i <= 100; i++) { users.push(createNewUser(i)); }

    this.dataSource = new MatTableDataSource(users);
  }

  ngAfterViewInit() {
    this.dataSource.paginator = this.paginator;
    this.dataSource.sort = this.sort;
  }

  applyFilter(filterValue: string) {
    filterValue = filterValue.trim(); 
    filterValue = filterValue.toLowerCase(); 
    this.dataSource.filter = filterValue;
  }
}

function createNewUser(id: number): IHeaders {
  const coutries = ['USA', 'UK', 'India', 'Singapore', 'London'];
  const country = coutries[Math.floor(Math.random() * coutries.length)];

  const genders = ['Male', 'Female'];
  const gender = genders[Math.floor(Math.random() * genders.length)];
  return {
    id: id,
    name: 'Nami ' + id,
    age: 21 + Math.round(Math.random() * 10),
    gender,
    country
  };
}

2 – materialtable.component.html

<div class="example-header">
  <mat-form-field>
    <input matInput (keyup)="applyFilter($event.target.value)" placeholder="Filter">
  </mat-form-field>
</div>

<div class="example-container mat-elevation-z8">

  <mat-table [dataSource]="dataSource" matSort>

    <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>

    <ng-container matColumnDef="age">
      <mat-header-cell *matHeaderCellDef mat-sort-header> Age </mat-header-cell>
      <mat-cell *matCellDef="let row"> {{row.age}} </mat-cell>
    </ng-container>

    <ng-container matColumnDef="gender">
      <mat-header-cell *matHeaderCellDef mat-sort-header> Gender </mat-header-cell>
      <mat-cell *matCellDef="let row" > {{row.gender}} </mat-cell>
    </ng-container>

    <ng-container matColumnDef="country">
      <mat-header-cell *matHeaderCellDef mat-sort-header> Country </mat-header-cell>
      <mat-cell *matCellDef="let row" > {{row.country}} </mat-cell>
    </ng-container>

    <mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
    <mat-row *matRowDef="let row; columns: displayedColumns;">
    </mat-row>
  </mat-table>

  <mat-paginator [pageSizeOptions]="[5, 10, 25, 100]"></mat-paginator>
</div>

3- materialtable.component.css

.example-container {
  display: flex;
  flex-direction: column;
  min-width: 300px;
}

.example-header {
  min-height: 64px;
  padding: 8px 24px 0;
}

.mat-form-field {
  font-size: 14px;
  width: 100%;
}

.mat-table {
  overflow: auto;
  max-height: 500px;
}

After adding these files in your project install and start the project

npm install

npm start

Once everything is OK with no error, then after start open the url http://localhost:4200 in browser. you should see the table with pagination, filter and sorting.

The working example code I have added on my github https://github.com/infotechseo/angular-table-with-pagination-filter-sorting

For any query or doubt please comment in the comment section.

FAQs

Q1. How to set pagination in DataTable?

Ans: To set up pagination in a DataTable using Angular, you can use the Angular DataTables library, such as ngx-datatable.

Read also How to load Balance Node.js Application with Docker and NGINX

Similar Posts