我在一个页面中有两个Angular Data Tables。我从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;
});
}
组件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>
答案 0 :(得分:1)
而不是使用@ViewChild(MatSort)
使用@ViewChildren(MatSort)
。
这将为您提供包含两个MatSort实例的QueryList<MatSort>
。
您也可以这样做以获取MatPaginator的两个实例。
有关ViewChildren和QueryList的更多信息,请访问:https://netbasal.com/understanding-viewchildren-contentchildren-and-querylist-in-angular-896b0c689f6e
答案 1 :(得分:0)
你可以这样使用它:
IN ts:
@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"