Angular Material Table with pagination sorting and filtering example

Angular Material Table Example with Pagination, Sorting & Filtering (Step-by-Step)

Prerequisites

Add Angular Material

ng add @angular/material

What We Are Going to Build

Step 1: Import Angular Material Modules

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { FormsModule } from '@angular/forms';

// Angular Material Modules
import { MatTableModule } from '@angular/material/table';
import { MatPaginatorModule } from '@angular/material/paginator';
import { MatSortModule } from '@angular/material/sort';
import { MatInputModule } from '@angular/material/input';

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

@NgModule({
  declarations: [AppComponent],
  imports: [
    BrowserModule,
    BrowserAnimationsModule,
    FormsModule,
    MatTableModule,
    MatPaginatorModule,
    MatSortModule,
    MatInputModule
  ],
  bootstrap: [AppComponent]
})
export class AppModule {}

Explanation:

import { bootstrapApplication } from '@angular/platform-browser';
import { provideAnimations } from '@angular/platform-browser/animations';
import { importProvidersFrom } from '@angular/core';
import { AppComponent } from './app/app.component';

import { MatTableModule } from '@angular/material/table';
import { MatPaginatorModule } from '@angular/material/paginator';
import { MatSortModule } from '@angular/material/sort';
import { MatInputModule } from '@angular/material/input';
import { FormsModule } from '@angular/forms';

bootstrapApplication(AppComponent, {
  providers: [
    provideAnimations(),
    importProvidersFrom(
      MatTableModule,
      MatPaginatorModule,
      MatSortModule,
      MatInputModule,
      FormsModule
    )
  ]
});

Step 2: Component Logic

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

// Product interface
export interface Product {
  id: number;
  name: string;
  price: number;
}

// Sample data
const PRODUCT_DATA: Product[] = [
  { id: 1, name: 'Laptop', price: 1200 },
  { id: 2, name: 'Mobile', price: 800 },
  { id: 3, name: 'Tablet', price: 500 },
  { id: 4, name: 'Headphones', price: 150 },
  { id: 5, name: 'Smartwatch', price: 200 },
  { id: 6, name: 'Monitor', price: 400 },
  { id: 7, name: 'Keyboard', price: 50 },
  { id: 8, name: 'Mouse', price: 30 },
  { id: 9, name: 'Printer', price: 250 },
  { id: 10, name: 'Camera', price: 600 },
  { id: 11, name: 'Speaker', price: 180 },
  { id: 12, name: 'Router', price: 120 },
  { id: 13, name: 'External Hard Drive', price: 100 },
  { id: 14, name: 'Microphone', price: 90 },
  { id: 15, name: 'Projector', price: 700 }
];

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements AfterViewInit {
  displayedColumns: string[] = ['id', 'name', 'price'];
  dataSource = new MatTableDataSource<Product>(PRODUCT_DATA);

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

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

  applyFilter(event: Event) {
    const filterValue = (event.target as HTMLInputElement).value;
    this.dataSource.filter = filterValue.trim().toLowerCase();
  }
}

Step 3: Create the Table in HTML (Template)

<div style="margin:20px;">
  <h2 class="title-primary">Product Table</h2>

  <!-- Search Box -->
  <mat-form-field appearance="outline" color="accent" class="search-box">
    <mat-label>Search Products</mat-label>
    <input matInput (keyup)="applyFilter($event)" placeholder="Type to search">
  </mat-form-field>

  <!-- Table -->
  <table mat-table [dataSource]="dataSource" matSort class="mat-elevation-z8 colorful-table">

    <!-- ID Column -->
    <ng-container matColumnDef="id">
      <th mat-header-cell *matHeaderCellDef mat-sort-header class="header-blue">ID</th>
      <td mat-cell *matCellDef="let element">{{element.id}}</td>
    </ng-container>

    <!-- Name Column -->
    <ng-container matColumnDef="name">
      <th mat-header-cell *matHeaderCellDef mat-sort-header class="header-pink">Name</th>
      <td mat-cell *matCellDef="let element">{{element.name}}</td>
    </ng-container>

    <!-- Price Column -->
    <ng-container matColumnDef="price">
      <th mat-header-cell *matHeaderCellDef mat-sort-header class="header-red">Price ($)</th>
      <td mat-cell *matCellDef="let element">{{element.price}}</td>
    </ng-container>

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

  <!-- Pagination -->
  <mat-paginator [pageSizeOptions]="[2, 5, 10]" showFirstLastButtons color="primary"></mat-paginator>
</div>

Step 4: Run the Project

ng serve --open
Colorful Angular Material table displaying products with sortable columns, search box, and pagination controls

Conclusion

Related Articles

Leave a Comment

Your email address will not be published. Required fields are marked *