材料表组件在销毁时抛出错误

问题描述

我正在将应用程序升级到 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,这是否意味着我必须定义一个无数据行? (由于下一行代码,还有页脚和页眉) 或者我可以保持我的模板干净并以某种方式避免这个错误吗?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)