首页 > 解决方案 > 如何在 Angular 上使用 ngIf 进行分页?

问题描述

我尝试过使用 setTimeout(),甚至尝试过使用 [hidden] 而不是 ngIf。我还尝试将分页器放在包裹在 ngIf 中的元素之外。随着我做更多的研究,我会更新我的问题,但如果有人能指出我正确的方向,那就太好了。下面是 HTML 代码:

    <div fxLayout="row" fxLayoutAlign="center" class="report-container">
    <mat-card fxFlex.lg="98" fxFlex.md="98" fxFlex.sm="98" fxFlex.xs="98" *ngIf="!loading">
    <div fxLayout="row" fxLayoutAlign="space-between none">
      <mat-form-field>
        <mat-label>Report Type</mat-label>
        <mat-select [value]="reportOptions[0].path">
          <mat-option *ngFor="let option of reportOptions" [value]="option.path" routerLink="{{ option.link }}">
            {{ option.path }}</mat-option
          >
        </mat-select>
      </mat-form-field>

      <mat-search-bar matInput (keyup)="applyFilter($event.target.value)"></mat-search-bar>
    </div>

    <mat-table [dataSource]="dataSource" matSort>
      <ng-container matColumnDef="column1">
        <th mat-header-cell *matHeaderCellDef mat-sort-header>Column1</th>
        <td mat-cell *matCellDef="let element">
          <div class="mat-conventions text-data">
            {{ element.column1 }}
          </div>
        </td>
      </ng-container>

      <ng-container matColumnDef="column2">
        <th mat-header-cell *matHeaderCellDef mat-sort-header>Column2</th>
        <td mat-cell *matCellDef="let element">
          <div class="mat-conventions text-data">
            {{ element.column2 }}
          </div>
        </td>
      </ng-container>

      <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
      <tr mat-row *matRowDef="let row; columns: displayedColumns"></tr>
    </mat-table>

    <mat-paginator [pageSizeOptions]="[10, 25, 50]" showFirstLastButtons></mat-paginator>
  </mat-card>

  <div fxFlex.lg="98" fxFlex.md="98" fxFlex.sm="98" fxFlex.xs="98" *ngIf="loading" fxFill>
    <div fxLayout="row" fxLayoutAlign="center center">
      <mat-spinner *ngIf="loading" class="spinner-loading"></mat-spinner>
    </div>
  </div>
</div>

这是带有 ngOnInit 和 ngAfterViewInit 的打字稿代码:

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

constructor(private apollo: Apollo) {}

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

ngAfterViewInit() {
  this.dataSource.sort = this.sort;
  this.dataSource.paginator = this.paginator
}

标签: angulartypescriptpaginationmat-table

解决方案


尝试设置this.dataSource.paginator = this.paginator之后this.loading = falsethis.dataSource.data = data

UPD:您需要更改AfterContentCheckedAfterContentInit添加它:

 private paginator: MatPaginator;
  @ViewChild(MatPaginator, {static: false}) set matPaginator(mp: MatPaginator) {
    this.paginator = mp;
    this.dataSource.paginator = this.paginator;
  }

示例:https ://stackblitz.com/edit/angular-afp7wg


推荐阅读