单个页面中的多个 Mat-Paginator(Angular 5 个数据 Table)

Multiple Mat-Paginator in a single page (Angular 5 Data Table)

我在一个页面中有两个 Angular 数据表。我正在从 Web 服务器(异步)获取数据。 我为此创建了一个独立的组件。 我的第一个 table 正确显示并绑定到排序和分页器,但第二个不起作用。虽然它显示了数据,但分页器和排序在第二个 table 上不起作用。有什么想法可能是什么问题吗?

我的组件 TS 文件:

displayedColumns = ['customerId', 'projectId'];
@Input() dataSource2 = new MatTableDataSource<ScheduledTest>();
private paginator: MatPaginator;
private sort: MatSort;

@ViewChild(MatPaginator) set matPaginator(mp: MatPaginator) {
this.paginator = mp;
this.dataSource2.paginator = this.paginator;
}

@ViewChild(MatSort) set matSort(mp: MatSort) {
this.sort = mp;
this.dataSource2.sort = this.sort;
}

ngOnInit() {
this.getAllCurrentTestCases();
}

getAllCurrentTestCases() {
this.isError = false;
this.isLoading = true;
this.httpService.getAllCurrentTestCases(this.userService.accountNumber, this.userService.authToken)
  .then((data: AutomatedTest[]) => {
    this.isLoading = false;
    this.dataSource2 = new MatTableDataSource<AutomatedTest>(data);
    this.dataSource.sort = this.sort;
  })
  .catch(error => {
    this.isError = true;
  });
}

组件 HTML:

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

<ng-container matColumnDef="customerId">
  <mat-header-cell *matHeaderCellDef mat-sort-header>
    <b> Customer ID </b>
  </mat-header-cell>
  <mat-cell *matCellDef="let element"> {{element.data.customerId | uppercase }} </mat-cell>
</ng-container>

<ng-container matColumnDef="projectId">
  <mat-header-cell *matHeaderCellDef mat-sort-header>
    <b> Project ID </b>
  </mat-header-cell>
  <mat-cell *matCellDef="let element"> {{element.data.projectId | uppercase}} </mat-cell>
</ng-container>
<mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
<mat-row *matRowDef="let row; columns: displayedColumns;" matRipple class="element-row" [cdkDetailRow]="row" [cdkDetailRowTpl]="tpl"
  (toggleChange)="onToggleChange($event)"></mat-row>
<!-- <mat-row *matRowDef="let row; columns: ['expandedDetail']; when: isExpansionDetailRow" [@detailExpand]="row.element == expandedElement ? 'expanded' : 'collapsed'"
    style="overflow: hidden">
  </mat-row> -->

我的渲染页面

<app-table-com></app-table-com>
<app-table-com></app-table-com>

使用 @ViewChildren(MatSort) 而不是 @ViewChild(MatSort)。 这将为您提供一个包含两个 MatSort 实例的 QueryList<MatSort>

您可以执行相同的操作来获取 MatPaginator 的两个实例。

更多关于 ViewChildren 和 QueryList 的信息:https://netbasal.com/understanding-viewchildren-contentchildren-and-querylist-in-angular-896b0c689f6e

你可以这样使用它:

输入:

@ViewChild('MatPaginator1') paginator: MatPaginator;
@ViewChild('MatPaginator2') paginator2: MatPaginator;

@ViewChild('sorter1') sorter1: MatSort;
@ViewChild('sorter2') sorter2: MatSort;

在html:

#MatPaginator1="matPaginator"
#MatPaginator2="matPaginator"

#sorter1="matSort"
#sorter2="matSort"