Implement Custom Sorting In Angular Material Table

Step1: create new application

ng new demo

Step2: install angular material in your project

ng add @angular/material

Step3: create new component

ng g c search

Step4: create commonService

ng g s commonservice

Step5: Write below code in your common.service.ts

import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';

@Injectable({
  providedIn: 'root',
})

export class CommonService {
  keySort: any;
  constructor() {
    this.keySort = (a: any, b: any, direction: any) => {
      direction = direction !== null ? direction : 1;

      if (a === b) {
        // If the values are the same, do not switch positions.
        return 0;
      }

      // If b > a, multiply by -1 to get the reverse direction.
      return a > b ? direction : -1 * direction;
    };
  }

  //Table sorting
  sortObj(sortKeys: any, position: any, name: any) {
    this.array_move(sortKeys, sortKeys.indexOf(name), position);
    return sortKeys;
  }

  array_move(arr: any, old_index: any, new_index: any) {
    if (new_index >= arr.length) {
      var k = new_index - arr.length + 1;
      while (k--) {
        arr.push(undefined);
      }
    }
    arr.splice(new_index, 0, arr.splice(old_index, 1)[0]);
    return arr; // for testing
  }

  multiSort(array: any, sortObject: any = {}, sortKeys: any) {
    array.sort((a: any, b: any) => {
      let sorted = 0;
      let index = 0;

      // Loop until sorted (-1 or 1) or until the sort keys have been processed.
      while (sorted === 0 && index < sortKeys.length) {
        const key = sortKeys[index] as any;
        if (key) {
          const direction = sortObject[key];
          sorted = this.keySort(a[key], b[key], direction);
          index++;
        }
      }
      return sorted;
    });
    return array;
  }
}

Step6: write below code in your search.component.html

<div class="main">
  <div class="example-container mat-elevation-z8">
    <div class="example-table-container">
      <mat-table [dataSource]="dataSource" class="example-table" matSort matSortDisableClear #searchTable>
        <!-- Position Column -->
        <ng-container matColumnDef="name">
          <th *matHeaderCellDef mat-sort-header class="name_width_header" (click)="sortCol('name')"> Name </th>
          <td *matCellDef="let element" class="name_width pointer" [style.background-color]="element.flag ? '#272727' : '#171717'"  (click)="getCaseId(element.id,element.name)" > {{element.name}} </td>
        </ng-container>
        <!-- Name Column -->
        <ng-container matColumnDef="desc">
          <th *matHeaderCellDef mat-sort-header class="Description_width_header" (click)="sortCol('desc')"> Description </th>
          <td *matCellDef="let element" class="Description_width pointer" [style.background-color]="element.flag ? '#272727' : '#171717'" (click)="getCaseId(element.id,element.name)"> {{element.desc}} </td>
        </ng-container>
        <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
        <tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
      </mat-table>
    </div>
  </div>
</div>

Here, If each row click than call sortCol(‘name’) function. and pass field name in your function.

Step7: Write below code in your search.component.ts

import { Component, ElementRef, OnInit, ViewChild } from '@angular/core';
import { ChangeDetectorRef } from '@angular/core';
import { CommonService } from 'src/app/services/common.service';
import { SearchService } from 'src/app/services/search/search.service';
import { searchCase } from 'src/app/dtos/searchdtos/cases';
import { debounceTime, fromEvent, Subscription } from 'rxjs';
import { Router } from '@angular/router';

@Component({
  selector: 'app-search',
  templateUrl: './search.component.html',
  styleUrls: ['./search.component.css']
})

export class SearchComponent implements OnInit {

  @ViewChild('searchTable', {read: ElementRef}) public matTableRef!: ElementRef;
  displayedColumns = ['select','name','desc'];
   sortObjects = {
    id: 1,
    name: 1,
    description: 1
  } as any;
  sortKey = ['select', 'name', 'desc'];
  dataSource = this.ELEMENT_DATA;
  ELEMENT_DATA: searchCase[] = [];

  constructor(private changeDetector: ChangeDetectorRef, private _commonserviceService: CommonService) { }

  sortCol(name: any) {
    if (name) {
      this.sortObjects[name] = this.sortObjects[name] === 0 || this.sortObjects[name] === -1 ? 1 : -1;
    }
    this.sortKey = this._commonserviceService.sortObj(this.sortKey, 1, name);
    this.dataSource = this._commonserviceService.multiSort(this.dataSource, this.sortObjects, this.sortKey);
    this.dataSource = [...this.dataSource];
    this.changeDetector.detectChanges();
  }
}

export class searchCase implements IsearchCase {
    name: any;
    desc!: string;
    id!:Number
    flag!:boolean;
}

export interface IsearchCase {
    name: any;
    desc: string;
    id:Number;   
    flag:boolean;
  }

Step8: Now, Run Project npm start

 

 

Submit a Comment

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

Subscribe

Select Categories