MatSort 未定义 - Angular 5

Luc*_*par 9 angular-material angular angular5

我正在尝试在我的 angular 应用程序中实现一个 Material 表。分页和过滤器工作正常,但我无法对我的表格进行排序。我对 MatSort 的引用未定义。

我确实在 AppModule 中导入了它:

import {MatTableModule} from '@angular/material/table';
import {MatTooltipModule} from '@angular/material/tooltip';
import {MatButtonModule, MatCheckboxModule,MatPaginatorModule,MatInputModule} from '@angular/material';
import {MatSortModule} from '@angular/material/sort';

...
@NgModule({
  declarations: [...],
  imports: [   
     MatSortModule,
     MatTableModule,
     MatPaginatorModule,
     MatInputModule,
     ...
   ]
  })
Run Code Online (Sandbox Code Playgroud)

这是我的 component.ts:

import { Component, OnInit , ViewChild, AfterViewInit} from '@angular/core';
...
import {MatTableDataSource,MatSort,MatPaginator} from '@angular/material';
...
export class MyClass inplements OnInit, AfterViewInit{
  @ViewChild(MatSort) sort:MatSort;
  @ViewChild(MatPaginator) paginator:MatPaginator;
  ...
  ngAfterViewInit(){
     this.dataSource = new MatTableDataSource(this.fake_data);
     this.dataSource.paginator = this.paginator
     this.dataSource.sort = this.sort
  }
 ...
}
Run Code Online (Sandbox Code Playgroud)

这是我的组件 HTML:

<mat-form-field *ngIf="ready" class="width-80">
   <input matInput (keyup)="applyFilter($event.target.value)" placeholder="Filter">
</mat-form-field>
<mat-table #table class = "mat-elevation-z8 animate" matSort [dataSource]="dataSource" display:flex>
   <ng-container matColumnDef="fake_name">
       <mat-header-cell *matHeaderCellDef mat-sort-header class="columnTitle"><b>{{fake_label.name}}</b></mat-header-cell>
       <mat-cell *matCellDef="let fake;" class="cellContent">{{fake.name}}</mat-cell>
   </ng-container>
   <mat-header-row *matHeaderRowDef="fakeColumns"></mat-header-row>
   <mat-row *matRowDef="let row; columns: fakeColumns" class="animate"></mat-row>
</mat-table>
<mat-paginator [length]="length" [pageSize]="5" [pageSizeOptions]="[5,10,15,20,25,50,100]" showFirstLastButtons></mat-paginator>
Run Code Online (Sandbox Code Playgroud)

有谁知道我做错了什么?

Phi*_*ges 10

问题可以在apps.module.ts中修复:

import { MatPaginatorModule,MatSortModule } from '@angular/material';
Run Code Online (Sandbox Code Playgroud)

和:

imports: [
    ....
    MatPaginatorModule,        
    MatSortModule
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助。


Vic*_*ina 10

我遇到了同样的问题,并且在 Angular 的问题上找到了答案。

在我的特定情况下(以及 github 上那个人的情况),解决了删除标签*ngIf上的问题mat-table。我不确定,但也许这<mat-form-field *ngIf="ready" class="width-80">会造成一些麻烦。


Geo*_*Cs. 5

在 Angular 8 和 Material 6.4.1 中,如果您等待从服务接收数据,最简单、最好的解决方法就是设置 static : false而不是 true,如下所示:

@ViewChild(MatSort, { **static: false** }) sort: MatSort;
Run Code Online (Sandbox Code Playgroud)

就我而言,是对数据的 ngOnChanges 调用。

仅供参考:MatPaginator 也是如此。