Calling renderRows() on Angular Material Table
我正在尝试更新表中使用的数据后刷新Angular表。
文档说:"您可以通过调用表的renderRows()方法来触发对表的呈现行的更新。"但是它不像普通的子组件,我可以在其中使用" @ViewChild(MatSort)排序:MatSort;"。因为我不导入它。
如果我确实导入了它,然后尝试类似@ViewChild('myTable')myTable的方法:MatTableModule;然后我得到一个错误,指出该类型上不存在renderRows()。
如何调用此方法?谢谢!
我的表格代码段:
1 | <mat-table #table [dataSource]="dataSource" myTable class="dataTable"> |
确保您导入ViewChild和MatTable:
1 2 | import {Component, ViewChild} from '@angular/core'; import {MatTable} from '@angular/material'; |
然后,您可以使用ViewChild获得对该表的引用(请注意,MatTable上需要类型T-我刚刚使用了任何类型,但是如果您有类型表,则需要使用该类型:
1 | @ViewChild(MatTable) table: MatTable; |
然后,当您以任何方式修改表时,将需要调用renderRows()方法。
1 2 3 4 | delete(row: any): void { /* delete logic here */ this.table.renderRows(); } |
这是一个非常简单的工作示例:
https://stackblitz.com/edit/angular-bxrahf
我自己解决此问题时发现的一些资料来源:
- https://material.angular.io/cdk/table/api#CdkTable
- https://stackoverflow.com/a/49121032/8508548
@ViewChild('myTable') myTable: MatTableModule
您不应该查询字符串。这将查询引用(定义为
您应该导入要查询的组件,然后执行以下操作(根据您确切需要查询的组件进行更改):
1 | @ViewChild(MatTable) matTable: MatTable |
您可以使用
1 2 3 4 5 6 7 8 | import {Component, ViewChild} from '@angular/core'; import {MatTable} from '@angular/material'; @ViewChild(MatTable) table: MatTable; anyFunction(): void { this.table.renderRows(); } |
关于别人的答案。
或者您可以将服务传递到应用程序状态(@ ngrx / store)
例如:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | import { Component, OnInit } from '@angular/core'; import { MatTableDataSource } from '@angular/material/table'; import { Store } from '@ngrx/store'; import * as reducer from '../../app.reducer'; export class Test implements OnInit { dataSource = new MatTableDataSource(); constructor(private _store: Store<reducer.State>){} ngOnInit(): void { this._store.select(reducer.getYourSelectorCreated) .subscribe(res) => { <<<<--- Subscribe to listen changes on your"table data -state" this.dataSource.data = res; <<-- Set New values to table }); this._someService.fetchYourDataFromStateFunction(); <<-- Service to change the state } } |