Search code examples
angularangular-datatables

How to sort by date in Data table, Angular Material


I am using Angular Material, the first time. I am stuck with adding functionality to sort the row based on the date.. i.e the latest date should show on top & the oldest at the bottom.

I went through the angular material docs but not able to find any relevant information to do it.

This is my code:

view.component.html:

<div class="mat-elevation-z8">
    <table mat-table [dataSource]="dataSource"  matSort>

      <!-- Position Column -->
      <ng-container matColumnDef="position">
        <th mat-header-cell *matHeaderCellDef> Serial No. </th>
        <td mat-cell *matCellDef="let element"> {{element.position}} </td>
      </ng-container>

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

      <!-- Weight Column -->
      <ng-container matColumnDef="cost">
        <th mat-header-cell *matHeaderCellDef> Cost </th>
        <td mat-cell *matCellDef="let element"> {{element.cost}} </td>
      </ng-container>

      <!-- Symbol Column -->
      <ng-container matColumnDef="options">
        <th mat-header-cell *matHeaderCellDef> Options </th>
        <td mat-cell *matCellDef="let element"> <button (click)="getExpenseDetails()"mat-button color="primary">{{element.options}}</button> </td>
      </ng-container>

      <ng-container matColumnDef="date">
        <th mat-header-cell *matHeaderCellDef  mat-sort-header> Date </th>
        <td mat-cell *matCellDef="let element"> {{element.date | date}} </td>
      </ng-container>


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

    <mat-paginator [pageSizeOptions]="[5, 10, 20]" showFirstLastButtons></mat-paginator>
  </div><!-- <p>view works!</p> -->
<div class="mat-elevation-z8">
    <table mat-table [dataSource]="dataSource"  matSort>

      <!-- Position Column -->
      <ng-container matColumnDef="position">
        <th mat-header-cell *matHeaderCellDef> Serial No. </th>
        <td mat-cell *matCellDef="let element"> {{element.position}} </td>
      </ng-container>

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

      <!-- Weight Column -->
      <ng-container matColumnDef="cost">
        <th mat-header-cell *matHeaderCellDef> Cost </th>
        <td mat-cell *matCellDef="let element"> {{element.cost}} </td>
      </ng-container>

      <!-- Symbol Column -->
      <ng-container matColumnDef="options">
        <th mat-header-cell *matHeaderCellDef> Options </th>
        <td mat-cell *matCellDef="let element"> <button (click)="getExpenseDetails()"mat-button color="primary">{{element.options}}</button> </td>
      </ng-container>

      <ng-container matColumnDef="date">
        <th mat-header-cell *matHeaderCellDef  mat-sort-header> Date </th>
        <td mat-cell *matCellDef="let element"> {{element.date | date}} </td>
      </ng-container>


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

    <mat-paginator [pageSizeOptions]="[5, 10, 20]" showFirstLastButtons></mat-paginator>
  </div>

view.component.ts:

import {MatPaginator} from '@angular/material/paginator';
import {MatSort} from '@angular/material/sort';
import {MatTableDataSource} from '@angular/material/table';
import { Component, OnInit, ViewChild } from '@angular/core';
import {MatDialog} from '@angular/material/dialog';
import * as moment from 'moment';
import { DataSource } from '@angular/cdk/table';


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


export class ViewComponent implements OnInit {

  constructor(public dialog: MatDialog) {}
  displayedColumns: string[] = ['position', 'category', 'cost', 'options', 'date'];
  dataSource = new MatTableDataSource<PeriodicElement>(ELEMENT_DATA);

  @ViewChild(MatPaginator, {static: true}) paginator: MatPaginator;
  @ViewChild(MatSort, {static: true}) sort: MatSort;





  ngOnInit() {
    this.dataSource.paginator = this.paginator;
    console.log(new Date("1998-01-31").toDateString());
  }


}
export interface PeriodicElement {
  position: number;
  category: string;  
  cost: number;
  options: string;
  date: string;
}


const ELEMENT_DATA: PeriodicElement[] = [
  {position: 1, category: 'Hydrogen', cost: 1.0079, options: 'More', date: new Date("1998-01-31").toDateString() },
  {position: 2, category: 'Helium', cost: 4.0026, options: 'More', date: new Date("1998-01-31").toDateString()},
  {position: 3, category: 'Lithium',cost: 6.941, options: 'More', date: new Date("1998-01-31").toDateString()},
  {position: 4, category: 'Beryllium', cost: 9.0122, options: 'More', date: new Date("1998-01-31").toDateString()},
  {position: 5, category: 'Boron', cost: 10.811, options: 'More', date: new Date("1998-01-31").toDateString()},
  {position: 6, category: 'Carbon', cost: 12.0107, options: 'More', date: new Date("1998-01-31").toDateString()},
  {position: 7, category: 'Nitrogen',cost: 14.0067, options: 'More', date: new Date("1998-01-31").toDateString()},
  {position: 8, category: 'Oxygen', cost: 15.9994, options: 'More', date: new Date("1998-01-31").toDateString()},
  {position: 9, category: 'Fluorine',cost: 18.9984, options: 'More', date: new Date("1998-01-31").toDateString()},
  {position: 10, category: 'Neon', cost:1797, options: 'More', date: new Date("1998-01-31").toDateString()},
  {position: 11, category: 'Sodium', cost: 22.9897, options: 'More', date: new Date("1998-01-31").toDateString()},
  {position: 12, category: 'Magnesiumght', cost: 24.305, options: 'More', date: new Date("1998-01-31").toDateString()},
  {position: 13, category: 'Aluminum',cost: 26.9815, options: 'More', date: new Date("1998-01-31").toDateString()},
  {position: 14, category: 'Silicon',cost: 28.0855, options: 'More', date: new Date("1998-01-31").toDateString()},
  {position: 15, category: 'Phosphoruight', cost: 30.9738, options: 'More', date: new Date("1998-01-31").toDateString()},
  {position: 16, category: 'Sulfur', cost: 32.065, options: 'More', date: new Date("1998-01-31").toDateString()},
  {position: 17, category: 'Chlorine',cost: 35.453, options: 'More', date: new Date("1998-01-31").toDateString()},
  {position: 18, category: 'Argon', cost: 39.948, options: 'More', date: new Date("2000-01-31").toDateString()},
  {position: 19, category: 'Potassiumght', cost: 39.0983, options: 'More', date: new Date("1998-01-31").toDateString()},
  {position: 20, category: 'Calcium',cost: 40.078, options: 'More', date: new Date("1998-01-31").toDateString()}
];

This is how it looks as of now. I want it to be sorted according to the date..(latest on top, oldest on bottom)

I would really appreciate it if you can do the meaningful changes in the code. Thanks :)

enter image description here


Solution

  • Angular material table default sorting can be specified by passing matSortDirective and matSortDirection values to the table such as:

    <mat-table [dataSource]="dataSource" matSort matSortActive="name" matSortDirection="asc">
    

    Also add this.dataSource.sort = this.sort;.

    Example: https://stackblitz.com/edit/angular-table-sort-mainframe?file=app%2Ftable-pagination-example.ts

    In this example, the default sorting column is set to the 'name' column. In your case, just use the date column then matSortDirection="desc". Remove the mat-sort-header if you don't want the sorting arrow symbol at the top of the sorted column.