0
votes

I'm trying to implement sorting on my angular material data table.

It's displaying the data correctly but the sorting doesn't work, it doesn't even show the small arrow next to the header to indicate it's being sorted.

Here's my component

import { Component, OnInit, ViewChild, AfterViewInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { ToastrService } from 'ngx-toastr';
import { Project, Activity, LearningObjective } from '../../models';
import { AuthService } from '../../services/auth.service';
import { MatSort, MatTableDataSource } from '@angular/material';
import { Router } from '@angular/router';

@Component({
  selector: 'app-activities',
  templateUrl: './activities.component.html',
  styleUrls: ['./activities.component.scss']
})
export class ActivitiesComponent implements OnInit, AfterViewInit {

  @ViewChild(MatSort) sort: MatSort;

  projects          : Array<Project>;
  loading           : boolean = false;
  displayedColumns  : string[] = ['name', 'goal', 'date', 'actions'];
  dataSource;

  constructor(
    private http          : HttpClient,
    private toastr        : ToastrService,
    public authService    : AuthService,
    private router        : Router
  ) {}

  ngOnInit() {
    this.getProjects();
  }

  getProjects() {
    this.loading = true;
    this.http.get<Project[]>('projects')
    .subscribe(
      response => {
        this.projects = response;
        this.dataSource = new MatTableDataSource(this.projects);
        this.loading = false;
      },
      err => {
        this.toastr.error(err.error.message, 'Error');
        this.loading = false;
      }
    )
  }

  ngAfterViewInit() {
    this.dataSource.sort = this.sort;
  }
}

And my html

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

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

    <ng-container matColumnDef="goal">
      <th mat-header-cell *matHeaderCellDef mat-sort-header> Goal </th>
      <td mat-cell *matCellDef="let element"> {{element.goal}} </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}} </td>
    </ng-container>

    <ng-container matColumnDef="actions">
      <th mat-header-cell *matHeaderCellDef></th>
      <td mat-cell *matCellDef="let element">
        <div class="button-row">
          <button  mat-raised-button color="primary" [disabled]="loading ">
              <i class="fa fa-edit " *ngIf="!loading"></i>
              <i class="fa fa-spinner fa-spin " *ngIf="loading"></i>
            </button>
          <button mat-raised-button color="primary" (click)="deleteProject(element._id)" [disabled]="loading">
              <i class="fa fa-trash " *ngIf="!loading"></i>
              <i class="fa fa-spinner fa-spin " *ngIf="loading"></i>
            </button>
        </div>
        </td>
    </ng-container>

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

How do I correctly implement the sort in this case? Can't click the table headers like in a working example so I'm wondering what is missing here.

1
Make sure you're importing either NoopAnimationsModule or BrowserAnimationsModule from @angular/platform-browser/animations in order for the data show in time and the arrows show.David Avikasis

1 Answers

2
votes

It most likely won't work because your async request to load the data in the ngOnInit takes longer than for the component lifecycle hook ngAfterViewInit to be called. Therefore your dataSource is still undefined and the setting of the sorting won't work.

You could initially create a new MatTableDataSource with an empty array to get around this problem. When you declare the datasource in your component:

dataSource = new MatTableDataSource([]);

And then in your getProjects simply do this:

this.dataSource.data = this.projects;
this.dataSource.sort = this.sort;

Check out the stackblitz for a solution. I had to mock the HTTP request and used a delay to simulate the request.