垫子表的分页器不起作用

时间:2019-07-06 20:52:15

标签: angular typescript angular-material

我是不熟悉Angle和Typescript的人,我正在尝试用分页器设置表格。分页器数据集来自REST API。该API到目前为止已经可以使用,并且我可以成功获取数据。

很遗憾,分页器目前无法正常工作。

进口还可以。 我从REST服务获取数据后分配数据, 但我仍然收到此错误消息:

ERROR TypeError: Cannot set property 'paginator' of undefined

我在做什么错了?

 availableLanguages: ILanguage[];
  displayedColumns = ['language'];
  dataSource: MatTableDataSource<ILanguage>;

  @ViewChild(MatPaginator) paginator: MatPaginator;
  @ViewChild(MatSort) sort: MatSort;

  constructor(public service: DialectService) {}

  ngOnInit(): void {
    this.service.getLanguages()
      .subscribe((resp: ILanguage[]) => {
        this.availableLanguages = resp;
        this.dataSource = new MatTableDataSource(resp);
      });
  }


  /**
   * Set the paginator and sort after the view init since this component will
   * be able to query its view for the initialized paginator and sort.
   */
  ngAfterViewInit() {
    this.dataSource.paginator = this.paginator;
    this.dataSource.sort = this.sort;
  }



  applyFilter(filterValue: string) {
    filterValue = filterValue.trim(); // Remove whitespace
    filterValue = filterValue.toLowerCase(); // Datasource defaults to lowercase matches
    this.dataSource.filter = filterValue;
    console.log(this.dataSource.filter, filterValue);
  }
}

<!--   -->
<div class="example-header">
  <mat-form-field>
    <input matInput (keyup)="applyFilter($event.target.value)" placeholder="Filter">
  </mat-form-field>
</div>

<div class="example-container mat-elevation-z8">

  <mat-table [dataSource]="dataSource" matSort>

    <ng-container matColumnDef="language">
      <mat-header-cell *matHeaderCellDef mat-sort-header> Language </mat-header-cell>
      <mat-cell *matCellDef="let row"> {{row}} </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]="[1, 2, 25, 100]"></mat-paginator>
</div>

1 个答案:

答案 0 :(得分:0)

尝试将所有数据集初始化代码移至ngAfterViewInit中。如下所示。

availableLanguages: ILanguage[];
displayedColumns = ['language'];
dataSource: MatTableDataSource<ILanguage>;

@ViewChild(MatPaginator) paginator: MatPaginator;
@ViewChild(MatSort) sort: MatSort;

constructor(public service: DialectService) {}

ngOnInit(): void { }

ngAfterViewInit() {
    this.service.getLanguages()
        .subscribe((resp: ILanguage[]) => {
            this.availableLanguages = resp;
            this.dataSource = new MatTableDataSource(resp);
            this.dataSource.paginator = this.paginator;
            this.dataSource.sort = this.sort;
        });
}

由于对this.service.getLanguages()的调用是异步的,因此在ngAfterViewInit生命周期钩子触发时尚未完成。因此,当ngAfterViewInit尝试将paginator分配给this.dataSource时,它仍然是未定义的。