角材料数据表排序不起作用/未显示箭头

时间:2019-05-02 10:43:10

标签: angular angular-material

我正在尝试对角度材料数据表进行排序。

它可以正确显示数据,但是排序不起作用,甚至没有在标题旁边显示小箭头以指示正在排序。

这是我的组成部分

ftpServer = ftp://ftp.myServer.co.uk/mySite.co.uk/
ftpFolder = My Folder (Test)

还有我的html

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;
  }
}

在这种情况下,如何正确实现排序?无法像在工作示例中那样单击表标题,所以我想知道这里缺少什么。

2 个答案:

答案 0 :(得分:1)

这很可能无法正常工作,因为您的异步请求将数据加载到ngOnInit中比调用组件生命周期挂钩ngAfterViewInit花费的时间更长。因此,您的dataSource仍未定义,并且排序设置无效。

您最初可以使用空数组创建一个新的MatTableDataSource来解决此问题。在组件中声明数据源时:

dataSource = new MatTableDataSource([]);

然后在您的getProjects中执行以下操作:

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

查看   stackblitz   寻找解决方案。我不得不模拟HTTP请求并使用了延迟   模拟请求。

答案 1 :(得分:0)

    //try setTimeout instead of ngAfterViewInit


   setTimeout(
      () => {
        this.dataSource.sort = this.sort;
      }
    );
相关问题