Open In App

Angular Material Sort Header Component

Last Updated : 16 Jan, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Angular Material is a UI component library, developed by Google, in order to develop modern applications in a structured and responsive way by the Angular developers. By making use of this library, we can greatly increase the user experience of an end-user thereby gaining popularity for our application. This library contains modern ready-to-use elements which can be directly used with minimum or no extra code.

The <mat-sort-header> component is used to sort a table’s data based on ascending or descending order. For the sorting to work, we have to add <mat-sort-header> to every table header and provide an ID that will identify it. These table headers must be placed within a parent element with the matSort directive so that whenever we click any table header for sorting, an event known as matSortChange will be emitted that contains sorting direction and the ID of the column name for which it got triggered.

We can disable the sorting of a table in 2 ways:

  • We can add property matSortDisabled  on matSort directive, or
  • Add disabled attribute on any single table header

Syntax:

<table matSort (matSortChange)="sortData($event)">
   <tr>
     <th mat-sort-header="column_id">
         Column 1
     </th>
   </tr>
   <tr>
     <td>Data</td>
   </tr>
</table>

Installation Syntax:

In order to use the Basic Card Section in the Angular Material, we must have Angular CLI installed in the local machine, which will help to add and configure the Angular material library. After satisfying the required condition, type the following command on the Angular CLI:

ng add @angular/material

Please refer to the Adding Angular Material Component to Angular Application article for the detailed installation procedure.

Adding Sort-Header component:

To use the sort-header component, we need to import it into our component, as follows:

import { Sort } from '@angular/material/sort';

Then, we need to import this component into the app.module.ts file.

import {MatSortModule} from '@angular/material/sort';

Project Structure:

After successful installation, the project structure will look like the following image:

Project Structure

Project Structure

Example: The below example illustrates the implementation of the Angular Material Sort Header.

app.module.ts




import { CommonModule } from "@angular/common";
import { NgModule } from "@angular/core";
  
import { BrowserModule } from "@angular/platform-browser";
import { AppComponent } from "./app.component";
import { BrowserAnimationsModule } from
    "@angular/platform-browser/animations";
  
import { SortOverviewExampleComponent } from
    "./sort-overview-example/sort-overview-example.component";
import { MatSortModule } from "@angular/material/sort";
  
@NgModule({
  declarations: 
  [AppComponent, 
  SortOverviewExampleComponent],
  exports: [AppComponent],
  imports:
  [ CommonModule,
    BrowserAnimationsModule,
    BrowserModule,
    MatSortModule,
  ],
  bootstrap: [AppComponent],
})
export class AppModule {}


sort-overview-example.component.ts




import { Component, OnInit } from "@angular/core";
import { Sort } from "@angular/material/sort";
  
export interface Student {
  physics: number;
  maths: number;
  chemistry: number;
  name: string;
  roll_number: number;
}
  
@Component({
  selector: "app-sort-overview-example",
  templateUrl: "sort-overview-example.component.html",
  styleUrls: ["./sort-overview-example.component.css"],
})
export class SortOverviewExampleComponent implements OnInit {
  ngOnInit(): void {}
  school: Student[] = [
    { name: "Niall", physics: 91, chemistry: 86, maths: 84, roll_number: 4 },
    { name: "Liam", physics: 73, chemistry: 71, maths: 89, roll_number: 2 },
    { name: "Zayn", physics: 74, chemistry: 91, maths: 99, roll_number: 5 },
    { name: "Harry", physics: 82, chemistry: 80, maths: 92, roll_number: 3 },
    { name: "Louis", physics: 96, chemistry: 76, maths: 93, roll_number: 1 },
  ];
  
  sortedData: Student[];
  
  constructor() {
    this.sortedData = this.school.slice();
  }
  sortData(sort: Sort) {
    const data = this.school.slice();
    if (!sort.active || sort.direction === "") {
      this.sortedData = data;
      return;
    }
  
    this.sortedData = data.sort((a, b) => {
      const isAsc = sort.direction === "asc";
      switch (sort.active) {
        case "name":
          return compare(a.name, b.name, isAsc);
        case "roll_number":
          return compare(a.roll_number, b.roll_number, isAsc);
        case "maths":
          return compare(a.maths, b.maths, isAsc);
        case "physics":
          return compare(a.physics, b.physics, isAsc);
        case "chemistry":
          return compare(a.chemistry, b.chemistry, isAsc);
        default:
          return 0;
      }
    });
  }
}
  
function compare(a: number | string, b: number | string, isAsc: boolean) {
  return (a < b ? -1 : 1) * (isAsc ? 1 : -1);
}


sort-overview-example.component.html




<h1>GeeksforGeeks</h1>
<h3>matSort & mat-sort-header Example</h3>
<table matSort (matSortChange)="sortData($event)">
    <tr>
        <th mat-sort-header="roll_number">Roll No.</th>
        <th mat-sort-header="name">Student Name</th>
        <th mat-sort-header="maths">Mathematics</th>
        <th mat-sort-header="chemistry">Chemistry</th>
        <th mat-sort-header="physics">Physics</th>
    </tr>
    <tr *ngFor="let student of sortedData">
        <td>{{ student.roll_number }}</td>
        <td>{{ student.name }}</td>
        <td>{{ student.maths }}</td>
        <td>{{ student.chemistry }}</td>
        <td>{{ student.physics }}</td>
    </tr>
</table>


sort-overview-example-component.css




h1,
h3 {
  color: green;
  font-family: "Roboto", sans-serif;
  text-align: center;
}
table {
  font-family: "Open Sans", sans-serif;
  margin-left: 50px;
}


app.component.html




<app-sort-overview-example></app-sort-overview-example>


Output:

Angular Material Sort Header Component

Reference: https://material.angular.io/components/sort/overview



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads