TypeError: table.renderRows is not a function

TypeError: table.renderRows is not a function

我正在使用 Angular material 数据table 和数组作为数据源。我会使用文档中提到的 renderRows() 方法更新我的 table 每次数据更改。

我有我的 ts 文件

import { Component, OnInit } from '@angular/core';
import { MatTableDataSource } from '@angular/material';
import { AjouttextService } from '../ajouttext.service';
import { DataSource } from "@angular/cdk/collections";
import { Observable } from "rxjs/Observable";
import { nomchamp } from '../model';

@Component({
  selector: 'app-datatable',
  templateUrl: './datatable.component.html',
  styleUrls: ['./datatable.component.css']
})
export class DatatableComponent implements OnInit {

  constructor(private dataService: AjouttextService) { }
  data: nomchamp[] = [{ id: "33", text: "HAHA" }, { id: "55", text: "bzlblz" }];

  displayedColumns = ['text'];
  dataSource = new MatTableDataSource(this.data);
  //new UserDataSource(this.dataService);


  applyFilter(filterValue: string) {
    filterValue = filterValue.trim(); // Remove whitespace
    filterValue = filterValue.toLowerCase(); // MatTableDataSource defaults to lowercase matches
  }
  ngOnInit() {
  }
  ajoutText(newtext: string, table: any) { \ADD TEXT
    let noew: nomchamp = { id: "44", text: newtext };
    this.data.push(new);
    table.renderRows();
  }
}

HTML 文件,我在其中声明了#table 变量并将其传递给 ajoutText 函数

<form class="form">
  <mat-form-field class="textinput">
    <input #newtext matInput placeholder="Ajoutez votre texte" value="">
  </mat-form-field>
  <button type="button" mat-raised-button color="primary" (click)="ajoutText(newtext.value,table)">Ajouter</button>

</form>
<p>{{text}}</p>
<div class="example-container mat-elevation-z8">
  <mat-table #table [dataSource]="dataSource">
    <!-- Position Column -->
    <ng-container matColumnDef="text">
      <mat-header-cell *matHeaderCellDef> No. </mat-header-cell>
      <mat-cell *matCellDef="let element"> {{element.text}} </mat-cell>
    </ng-container>
    <mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
    <mat-row *matRowDef="let row; columns: displayedColumns;"></mat-row>
  </mat-table>
</div>

当我在输入中添加文本并单击按钮时出现此错误

ERROR TypeError: table.renderRows is not a function

看来您需要将 @angular-cdk 软件包更新到 5.2。

查看源代码后,renderRows 是从那个版本才添加的:

5.1 version of CdkTable source code -> 不包含 renderRows 方法。

5.2 version of CdkTable source code -> 包含一个 renderRows 方法。

(注意 MatTable 扩展了 CdkTable。)

我使用 ViewChild 使其工作。

首先你必须导入它:

import { ViewChild } from '@angular/core';

然后就在

之后
export class DatatableComponent implements OnInit {

您声明:

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

现在您可以访问它了,它应该有 renderRows 方法。