Calling renderRows() on Angular Material Table

允我心安 提交于 2019-12-08 23:37:25

问题


I'm trying to get my Angular Table to refresh after updating the data used in the table.

The docs say "you can trigger an update to the table's rendered rows by calling its renderRows() method." but it is not like a normal child component where I can use something "@ViewChild(MatSort) sort: MatSort;" since I do not import it.

If I do import it and try something like @ViewChild('myTable') myTable: MatTableModule; then I get an error that says that renderRows() does not exist on that type.

How can I call this method? Thanks!

My table code snippet:

<mat-table #table [dataSource]="dataSource" myTable class="dataTable">

回答1:


Make sure you import ViewChild and MatTable:

import {Component, ViewChild} from '@angular/core';
import {MatTable} from '@angular/material';

Then you can get a reference to the table using the ViewChild (note that a type T is required on MatTable - I just used any, but if you have a typed table, you will need to use that type:

@ViewChild(MatTable) table: MatTable<any>;

Then when you modify the table in any way you will need to call the renderRows() method.

delete(row: any): void {
  /* delete logic here */
  this.table.renderRows();
}

Here is a very simple working example: https://stackblitz.com/edit/angular-bxrahf

Some sources I found when solving this issue myself:

  • https://material.angular.io/cdk/table/api#CdkTable
  • https://stackoverflow.com/a/49121032/8508548



回答2:


@ViewChild('myTable') myTable: MatTableModule

You're not supposed to query for the string. This will query the reference (defined like <cmp #ref>). Also the type is wrong: you're not grabbing a module from the view, you're grabbing a component.

You should import the component you want to query and do the following (change according to which component exactly you need to query):

@ViewChild(MatTable) matTable: MatTable

The argument in the ViewChild decorator is the component you want to query and the type is just for your convenience -- you could omit it or say any, but you won't have any help from TypeScript if you do not do it so it's recommended to leave it.



来源:https://stackoverflow.com/questions/49284358/calling-renderrows-on-angular-material-table

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!