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

Ume*_*mer 5 angular-material angular-datatables angular angular5

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

我的组件 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;
  });
}
Run Code Online (Sandbox Code Playgroud)

组件 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> -->
Run Code Online (Sandbox Code Playgroud)

我的渲染页面

<app-table-com></app-table-com>
<app-table-com></app-table-com>
Run Code Online (Sandbox Code Playgroud)

Rav*_*hru 4

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

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

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

  • 有没有办法使用 id 来识别它们,而不是将它们称为 queryListArray[index]?...类似 queryListArray.getPaginator(id2) 之类的东西? (3认同)