【发布时间】:2021-02-18 08:08:20
【问题描述】:
这可能只是一个理解问题,但我不知道如何在我的 CdkTable 上调用 renderRows()。
如果我改用 MatTable,我似乎可以使用 ViewChild() 来访问 MatTable 并调用 renderRows () 这样说:
@ViewChild(MatTable) table: MatTable<string>;
并在其上调用 renderRows
this.table.renderRows();
ViewChild 似乎在使用现有类或想要使用带有 cdk-table 选择器的指令时效果很好
但是,如果我的 CDKTable 是这样使用的:
<table cdk-table [dataSource]="dataSource">
...
</table>
如何访问它以便在其上调用 renderRows()?
我在下面包含了我的组件以供参考
import { Component, Input, Directive } from '@angular/core';
import { BehaviorSubject, Observable } from 'rxjs';
import { DataSource } from '@angular/cdk/collections';
@Component({
selector: 'app-editable-dynamic-table',
templateUrl: './editable-dynamic-table.component.html',
styleUrls: ['./editable-dynamic-table.component.scss']
})
@Directive(
{ selector: '[cdk-table]' }
)
export class EditableDynamicTableComponent {
@Input() tableData: any[] = [];
@Input() displayedColumns;
@Input() dataSchema;
dataSource: TableDataSource | [] = [];
ngOnInit() {
this.dataSource = new TableDataSource(this.tableData);
}
addRow(): void {
this.tableData.push(
{
exampleElement: null,
exampleElement2: null
}
)
// this is where I want to call renderRows();
}
}
export class TableDataSource extends DataSource<any> {
constructor(private tableData: any[]) {
super();
}
data = new BehaviorSubject<any[]>(this.tableData);
connect(): Observable<any[]> {
return this.data;
}
disconnect() { }
}
这是我的模板
<app-button [reversePrimary]="true" (click)="addRow()" content="Add New Row"></app-button>
<table cdk-table [dataSource]="dataSource">
<ng-container cdkColumnDef="{{col}}" *ngFor="let col of displayedColumns">
<th cdk-header-cell *cdkHeaderCellDef>
{{col}}
</th>
<td cdk-cell *cdkCellDef="let element">
<input type="{{dataSchema[col]}}" value="{{element[col]}}">
</td>
</ng-container>
<tr cdk-header-row *cdkHeaderRowDef="displayedColumns"></tr>
<tr cdk-row *cdkRowDef="let row; columns: displayedColumns;"></tr>
</table>
【问题讨论】:
标签: angular web angular-material angular-cdk