【问题标题】:Material table component throws error on destroy材料表组件在销毁时抛出错误
【发布时间】:2021-04-18 12:05:15
【问题描述】:

我正在将应用程序升级到 Angular 10。 在我的一个组件中,我使用了一个材料表。在 Angular 9 应用程序中,我的 html 如下所示:

<table mat-table [dataSource]="tableData" matSort class="mat-elevation-z8">

它在那里工作正常,但是当我升级到 Angular 10(角度材料和角度)时,我收到一条错误消息:

core.js:4442 ERROR TypeError: Cannot read property 'elementRef' of
undefined
    at MatTable._applyNativeTableSections (table.ts:1098)
    at MatTable.ngOnInit (table.ts:471)

当我将 html 更改为:

  <mat-table [dataSource]="tableData" matSort class="mat-elevation-z8">
    
    <ng-container matColumnDef="date">
      <mat-header-cell *matHeaderCellDef mat-sort-header="date"> Date </mat-header-cell>
      <mat-cell *matCellDef="let element">{{dateAndTime(element.date)}}</mat-cell>
    </ng-container>
    <ng-container matColumnDef="type">
      <mat-header-cell *matHeaderCellDef mat-sort-header="type"> Type </mat-header-cell>
      <mat-cell *matCellDef="let element"> {{element.type}} </mat-cell>
    </ng-container>

    <mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
    <mat-row *matRowDef="let row; columns: displayedColumns" (click)="onRowClicked(row)" class="clickable-row">
    </mat-row>
  </mat-table>

页面呈现正常,排序工作,但是当我离开页面时,我得到了错误:

core.js:4442 ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'viewContainer' of undefined
TypeError: Cannot read property 'viewContainer' of undefined
    at MatTable.ngOnDestroy (table.ts:525)

对该错误的检查表明它抛出了表的 ngOnDestroy 函数。

// table.ts from angular material 10.2
ngOnDestroy() {
    this._rowOutlet.viewContainer.clear();
    this._noDataRowOutlet.viewContainer.clear();  // error occurs here!
    this._headerRowOutlet.viewContainer.clear();
    this._footerRowOutlet.viewContainer.clear();

    this._cachedRenderRowsMap.clear();

    this._onDestroy.next();
    this._onDestroy.complete();

    if (isDataSource(this.dataSource)) {
      this.dataSource.disconnect(this);
    }
  }

显然我没有 _noDataRowOutlet,这是否意味着我必须定义一个无数据行? (由于下一行代码,还有页脚和页眉) 或者我可以保持我的模板干净并以某种方式避免这个错误吗?

【问题讨论】:

  • 升级到 Angular 11 和 Angular Material 11 使问题消失。

标签: angular-material angular10 angular-material-table


【解决方案1】:

更新到 Angular 11 对我们没有帮助。 我们得到了同样的错误,说 _noDataRowOutlet 未定义。在我们的例子中,问题出现是因为我们覆盖了 CdkTable 模板并且没有添加 noDataRowOutlet 指令。 添加这个解决了我们的问题:

<ng-container noDataRowOutlet></ng-container>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-02-06
    • 1970-01-01
    • 2018-05-24
    • 1970-01-01
    • 1970-01-01
    • 2017-11-20
    • 1970-01-01
    相关资源
    最近更新 更多