如何获取 mat-table 的实例?
How do I get the instance of a mat-table?
我正在尝试获取 table 的实例,以便在更新数据源时使用 renderrows() 函数。
我已经尝试按照通常使用@ViewChild 的方式来做,但无论我做什么,它都是未定义的。
component.ts:
import {
MatTable,
MatTableDataSource,
MatPaginator,
MatSelectModule
} from "@angular/material";
@ViewChild(MatTable, { static: true }) playersTable: MatTable<any>;
addToDataSource(data) {
for (let index = 0; index < data.length; index++) {
this.dataSource.data.push(data[index]);
}
this.playersTable.renderRows(); // this.playersTable is undefined.
}
.html:
<div class="mat-elevation-z8">
<table
mat-table
#playersTable
[dataSource]="dataSource"
*ngIf="!loadingData; else loading"
class="row"
>
...
</table>
将 Id 提供给您的垫子-table
<table mat-table #playersTable[dataSource]="dataSource">
然后使用 ViewChild 可以访问 table 的实例。
而不是将数据推送到数据源,而是使用 new MatTableDataSource()
分配数据
@ViewChild('playersTable', {static:true}) playersMatTable: MatTable<any >;
addToDataSource(data){
this.dataSource = new MatTableDataSource(data);
this.playersTable.renderRows();
}
或者如果您想将数据添加到现有数据源,则需要在不使用实例的情况下刷新数据源。
addToDataSource(data) {
for (let index = 0; index < data.length; index++) {
this.dataSource.data.push(data[index]);
}
this.dataSource = [...this.dataSource]; //refresh the dataSource
}
我正在尝试获取 table 的实例,以便在更新数据源时使用 renderrows() 函数。
我已经尝试按照通常使用@ViewChild 的方式来做,但无论我做什么,它都是未定义的。
component.ts:
import {
MatTable,
MatTableDataSource,
MatPaginator,
MatSelectModule
} from "@angular/material";
@ViewChild(MatTable, { static: true }) playersTable: MatTable<any>;
addToDataSource(data) {
for (let index = 0; index < data.length; index++) {
this.dataSource.data.push(data[index]);
}
this.playersTable.renderRows(); // this.playersTable is undefined.
}
.html:
<div class="mat-elevation-z8">
<table
mat-table
#playersTable
[dataSource]="dataSource"
*ngIf="!loadingData; else loading"
class="row"
>
...
</table>
将 Id 提供给您的垫子-table
<table mat-table #playersTable[dataSource]="dataSource">
然后使用 ViewChild 可以访问 table 的实例。 而不是将数据推送到数据源,而是使用 new MatTableDataSource()
分配数据 @ViewChild('playersTable', {static:true}) playersMatTable: MatTable<any >;
addToDataSource(data){
this.dataSource = new MatTableDataSource(data);
this.playersTable.renderRows();
}
或者如果您想将数据添加到现有数据源,则需要在不使用实例的情况下刷新数据源。
addToDataSource(data) {
for (let index = 0; index < data.length; index++) {
this.dataSource.data.push(data[index]);
}
this.dataSource = [...this.dataSource]; //refresh the dataSource
}