材料数据表排序和分页不起作用

时间:2019-09-19 21:25:31

标签: angular angular-material

我正在使用Angular Material Data Table,但是无法使sortpagination正常工作。我创建了一个共享组件,该组件将与不同的数据集(因此具有不同的列名等)重复使用多次。表标题和行显示得很好(超过480行),但是当我单击排序按钮时,什么也没有发生,并且分页按钮被禁用。但是我无法弄清楚自己在做什么。

"dependencies": {
    "@angular/cdk": "~8.1.4",
    "@angular/common": "~8.2.4",
    "@angular/compiler": "~8.2.4",
    "@angular/core": "~8.2.4",
    "@angular/material": "^8.1.4"
},
"devDependencies": {
    "@angular/cli": "~8.3.3",
    "@angular/compiler-cli": "~8.2.4",
}

html

<div *ngIf="dataLoaded" class="example-container mat-elevation-z8">
    <mat-table #table [dataSource]="dataSource" matSort>
      <ng-container *ngFor="let col of displayedColumns" [matColumnDef]="col">
        <mat-header-cell *matHeaderCellDef mat-sort-header> {{col}} </mat-header-cell>
        <mat-cell *matCellDef="let data">
          <!--  for mobile devices the columns collapse and each column is a row -->
          <span class="mobile-label">{{col}}:</span>
          {{data[col]}}
        </mat-cell>
      </ng-container>
      <mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
      <mat-row *matRowDef="let row; columns: displayedColumns;"></mat-row>
    </mat-table>
    <mat-paginator
      [pageSizeOptions]="pageSizeOptions"
      showFirstLastButtons>
    </mat-paginator>
</div>

组件

@ViewChild(MatPaginator, {static: true})  paginator: MatPaginator;
@ViewChild(MatSort, {static: true})       sort: MatSort;

dataLoaded = false;
dataSource;
displayedColumns; 
pageSizeOptions: number[] = [];
tableData = [
    {
        email: "brk@gmail.com"
        id: 1
        name: "B. Reurk"
    },
    {
        email: "john@gmail.com"
        id: 2
        name: "J. Smith"
    },
    // another 480 results which show in the table just fine
];

ngOnInit()
{
    this.dataSource = new MatTableDataSource(this.tableData);
    for (let i = 25; i <= this.tableData.length + 25; i += 25) {
    this.pageSizeOptions.push(i);
}
    this.displayedColumns = ['email', 'id', 'name'];
    this.dataSource.sort = this.sort;
    this.dataSource.paginator = this.paginator;
}

1 个答案:

答案 0 :(得分:0)

我知道了。我必须删除包裹表的*ngIf,这很烂,因为现在我无法显示加载消息,但是可以!

<div class="example-container mat-elevation-z8">
    <mat-table #table [dataSource]="dataSource" matSort>
      <ng-container *ngFor="let col of displayedColumns" [matColumnDef]="col">
        <mat-header-cell *matHeaderCellDef mat-sort-header> {{col}} </mat-header-cell>
        <mat-cell *matCellDef="let data">
          <!--  for mobile devices the columns collapse and each column is a row -->
          <span class="mobile-label">{{col}}:</span>
          {{data[col]}}
        </mat-cell>
      </ng-container>
      <mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
      <mat-row *matRowDef="let row; columns: displayedColumns;"></mat-row>
    </mat-table>
    <mat-paginator
      [pageSizeOptions]="pageSizeOptions"
      showFirstLastButtons>
    </mat-paginator>
</div>