2

I created a datatable using ng generate @angular/material:table demoTable.

I have to sort by the date column. In the previous Angular versions I was able to use sortingDataAccessor for this purpose but for some reasons, I am not able to use that here.

Has anyone tried that using Angular 7 (more specifically after using the ng generate command to create the DataTable) ?

2
  • Did you look at this material.angular.io/components/sort/api ? Your question is not so clear to me. Are you able to sort? if so, the problem when sorting a date column? Commented Dec 6, 2018 at 12:26
  • @benshabatnoam I am not able to sort the date column Commented Dec 6, 2018 at 12:53

2 Answers 2

2

Take this steps and you should be able to sort your date column:

HTML:

  1. Add MatSortModule

    import {MatSortModule} from '@angular/material/sort';
    
    imports: [
      ...
      MatSortModule
      ...
    
  2. Add matSort to your tabel

    <table matSort ...
    
  3. Add mat-sort-header to your column th

    <th mat-sort-header="date"
    

Having this your column will emit the matSortChange event

  1. Register matSortChange event

    <table matSort (matSortChange)="sortData($event)">
    

TS:

  1. Implement sortData() your way, something like this:

    sortData(event) {
      this.(your-list) = this.(your-list).sort((a, b) => {
        return a.date > b.date ? 1 : -1;
      }
    }
    

You can see this in greater details in Angular Material Docs

Also, created this DEMO for you in case you get messed up with this

Sign up to request clarification or add additional context in comments.

Comments

1

You can do the sort usling MatSort like following:

import { MatSort, MatTableDataSource } from '@angular/material';

in your html:

 <mat-table #matSort="matSort" matSort>

in your ts component declare:

sortableList: MatSort;

@ViewChild('matSort') set yourDataSource(ms: MatSort) {

    this.sortStudentDetails = ms;
    yourDataSoruce = new MatTableDataSource(yourList);
    yourDataSoruce.sort = this.sortableList;
  }

this should work for all columns types.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.