角材料数据表未排序?

时间:2019-08-21 20:35:32

标签: javascript angular typescript angular-material

[STACKBLITS LINK] I'm attempting a minimal angular material data table with sorting

我添加了MatSortModule,在类中实现了@ViewChild,添加了指令,设置了dataSource.sort属性等。当我将鼠标悬停在表格上时,我得到了箭头,但是数据没有排序。

有想法吗?

    import { Component, OnInit, ViewChild } from '@angular/core';
    import { MatTableDataSource, MatSort } from "@angular/material";

    class Todo {
      id: string;
      description: string;
      complete: boolean;
    }
    @Component({
      selector: 'my-app',
      templateUrl: './app.component.html',
      styleUrls: ['./app.component.css']
    })
    export class AppComponent implements OnInit {
      @ViewChild(MatSort, {static: false}) sort: MatSort;

      /**
      * Control column ordering and which columns are displayed.
      */
      displayedColumns:string[] =  ['id'];
      dataSource: MatTableDataSource<Todo>;

      ngOnInit() {
        const todos: Todo[] = [
          { id: '123', description: 'Complete me!', complete: false },
          { id: '321', description: 'You Completed me!', complete: true }];
        this.dataSource = new MatTableDataSource(todos);
        this.dataSource.sort = this.sort;
      }
    }


    <mat-table class="mat-elevation-z8" [dataSource]="dataSource" matSort>
      <ng-container matColumnDef="id">
        <mat-header-cell *matHeaderCellDef mat-sort-header>ID</mat-header-cell>
        <mat-cell *matCellDef="let row;">{{row.id}}</mat-cell>
      </ng-container>
      <mat-header-row *matHeaderRowDef="displayedColumns">
      </mat-header-row>
      <mat-row *matRowDef="let row; columns: displayedColumns"></mat-row>
    </mat-table>

2 个答案:

答案 0 :(得分:2)

ViewChild的{​​{1}}在MatSort处是undefined,因为该视图尚未初始化。要解决此问题,请使用ngOnInit生命周期挂钩初始化视图后,在MatSort上设置dataSource

ngAfterViewInit

答案 1 :(得分:1)

我遇到了同样的问题,您需要设置MatSort。  这就是我解决的方法

@ViewChild(MatSort, {static: false}) set  sortMeeting (ms: MatSort){
this._sort = ms;
this.renewDataSource(); }

............................................

ngOnInit(){
this.dataSource = new MatTableDataSource(todos);
this.renewDataSource();
}


renewDataSource() {
this.dataSource.sort = this._sort;
}

我希望它会有所帮助。 :)