MatSort is undefined - Angular 5
我正在尝试在我的角度应用程序中实现Material表。 分页和筛选器工作正常,但是我无法对表格进行排序。 我对MatSort的引用是未定义的。
我确实将其导入AppModule中:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | 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, ... ] }) |
这是我的component.ts:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | 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 } ... } |
这是我的组件HTML:
1 2 3 4 5 6 7 8 9 10 11 12 | <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">{{fake_label.name}}</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> |
有人知道我在做什么错吗?
可以解决的问题可以添加到apps.module.ts中:
1 | import { MatPaginatorModule,MatSortModule } from '@angular/material'; |
和:
1 2 3 4 | imports: [ .... MatPaginatorModule, MatSortModule |
希望这可以帮助。
使用Angular 8和Material 6.4.1,如果您等待从服务中接收数据,则最简单,最佳的修复方法是将static:false而不是true设置为:
@ViewChild(MatSort,{static:false})排序:MatSort;
以我为例,是一个ngOnChanges数据调用。
仅供参考:对于MatPaginator同样如此。
问题是由于
1 | ngOnChanges(){ this.datasource.sort = sort; this.datasource.paginator = paginator; } |
或者,如果要在同一组件中更改
1 | ngOnInit(){ this.datasource.sort = sort; this.datasource.paginator = paginator; this.ready=false; } |
最后,用一些默认值初始化
1 | datasource=new MatTableDataSource([]); |
我遇到了同样的问题,并且找到了有关Angular问题的答案。
在我的特定情况下(以及该家伙在github上的情况),解决了删除
我的解决方案是: