Angular Material data table sorting not working/no arrows shown

假如想象 提交于 2021-02-05 09:30:07

问题


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:


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.



来源:https://stackoverflow.com/questions/55950684/angular-material-data-table-sorting-not-working-no-arrows-shown

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!