Angular Material 12 Table, Sorting, Searching & Pagination
Angular Material Data Table: Server Side Sort, Search and Pagination
Jameer Khan
This article is originally published to my blog: StackBlogger- Angular Material 12 Table, Sorting, Searching & Pagination
Angular Material is a high quality UI Components to use as an alternate for Bootstrap or any other UI frameworks. Angular Material provides various components to work with. It has its own set of components like Data Tables, Buttons, Popups, Cards and many more.
More info about Angular is here: Angular Material Official Link
In this article we will learn about Angular Material, Data Table, Data Sources, matColumnDef, Sort and Pagination details. I have used Angular 12 and Angular Material 12.2.8 for this example.
Download the complete code from Github here: Repo Link
Before starting the article, let’s look into some common questions about Angular Material.
What is Angular Material Table?
It is a table that provides mat designed data tables in rows and columns. Its similar to HTML table but with more features and designs. It has its own tags and attributes.
What is DataSource in Angular Material?
A datasource is a combined code to handle data retrieval, sorting, filtering, pagination etc things. It contains all logics to work with a DataTable in Angular Material.
What is matColumnDef in Angular?
It is a column definition in mat-table. It defines the set of cells available for the column in material table.
Let’s start the article.
Sit tight! You are going to start a pretty big tutorial 🙂
Create Angular Material DataTable
1. Add Material into your Angular project
ng add @angular/material

2. Import Table Module
Import the material modules into app.module.ts file (or any other file in case you are using a shared module file). As we need to implement the sorting as well so I am importing the MatSortModule along with MatCardModule (Card Module will make the UI a little better).
import { MatTableModule } from '@angular/material/table';
import { MatSortModule } from '@angular/material/sort';
import { MatCardModule } from '@angular/material/card';
@NgModule ({
imports: [ MatTableModule, MatSortModule, MatCardModule, // other modules here
]})
class AppModule {}
3. Create a Service file
Next we have to create a app.service.ts file with getSampleData method. I am using Github Search API to fetch the data. You can replace it with your actual API.
import { Injectable } from "@angular/core";import { HttpClient } from '@angular/common/http';import { Observable } from "rxjs";import { GithubApi } from "./table/table.component";import { SortDirection } from "@angular/material/sort"; @Injectable()export class AppService { constructor(private httpClient: HttpClient) { } getSampleData(sort: string, order: SortDirection, page: number): Observable<GithubApi> { return this.httpClient.get<GithubApi>(`https://api.github.com/search/issues?q=repo:angular/components&sort=${sort}&order=${order}&page=${page + 1}`); }}
4. Create Component and Consume API
import { AfterViewInit, Component, ViewChild } from '@angular/core';import { MatSort } from '@angular/material/sort';import { of } from 'rxjs';import { startWith, switchMap, catchError, map } from 'rxjs/operators';import { AppService } from '../app.service'; export interface GithubApi { items: GithubIssue[]; total_count: number;} export interface GithubIssue { created_at: string; number: string; state: string; title: string;} @Component({ selector: 'app-table', templateUrl: './table.component.html', styleUrls: ['./table.component.scss']})export class TableComponent implements AfterViewInit { displayedColumns: string[] = ['created', 'state', 'number', 'title']; data: GithubIssue[] = []; @ViewChild(MatSort) sort!: MatSort; constructor(private appService: AppService) { } ngAfterViewInit() { // If the user changes the sort order, reset back to the first page. this.sort.sortChange.subscribe(() => 0); this.sort.sortChange .pipe( startWith({}), switchMap(() => { return this.appService!.getSampleData(this.sort.active, this.sort.direction, 0) .pipe(catchError(() => of(null))); }), map(data => { if (data === null) { return []; } return data.items; }) ).subscribe(data => this.data = data); }}
Check the step by step implementation on my blog: Angular Material 12 Table, Sorting, Searching & Pagination
Download the complete code from Github here: Repo Link
Also Read:
RxJS forkJoin: Definition and Real World Uses
Real World Examples of 5 Common Observable Operators
5 Best Ways To Optimize Angular For Scaling (2021)
7 Best Ways To Improve Angular Code (2021)
5 Great SEO Ideas To Improve Angular Website Ranking
Upvote
Jameer Khan
Founder and Author at StackBlogger.

Related Articles