You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular Material v6 Mat-Footer实现报错:Cannot read property 'template' of undefined

解决Angular 6 Mat-Table页脚行报错及显示异常问题

嘿,我帮你排查了下这个问题,你遇到的ERROR TypeError: Cannot read property 'template' of undefined错误,还有表格无数据、列标题旁的"T"符号,都是几个小细节没处理对导致的,咱们一步步解决:

1. 错误根源分析

你给<mat-footer-row>指定了所有列(tableColumns),但只有total这一列定义了页脚单元格模板,其他列没有对应的mat-footer-cell。Angular CDK的表格组件在渲染页脚行时,会遍历tableColumns里的每一列,找不到对应列的页脚模板就会抛出这个"template未定义"的错误。另外你还误用了普通的<td>标签来写页脚单元格,这不符合Material Table的组件语法要求。

2. 分步解决方案

(1)修正页脚单元格的标签

把你代码里的:

<td mat-footer-cell *matFooterCellDef>100</td>

改成Material Table要求的<mat-footer-cell>标签:

<mat-footer-cell *matFooterCellDef style="width: 15%; flex: none">100</mat-footer-cell>

(2)处理页脚行的列定义(二选一)

这里有两种方式适配你的需求:

  • 方式一:只渲染有页脚内容的列
    如果不需要页脚行占满整个表格宽度,只显示total列的页脚内容,那就单独定义一个页脚列数组:
    在组件的.ts文件里添加:

    footerColumns = ['total'];
    

    然后把页脚行的代码改成:

    <mat-footer-row *matFooterRowDef="footerColumns"></mat-footer-row>
    
  • 方式二:让页脚行占满所有列
    如果需要页脚行和表头、数据行一样宽,那就要给tableColumns里的每一列都添加页脚单元格(空的也可以)。比如你还有name列的话,要补上:

    <ng-container matColumnDef="name">
      <mat-header-cell *matHeaderCellDef mat-sort-header>Name</mat-header-cell>
      <mat-cell *matCellDef="let item">{{item.name}}</mat-cell>
      <!-- 添加空的页脚单元格 -->
      <mat-footer-cell *matFooterCellDef></mat-footer-cell>
    </ng-container>
    

    这样tableColumns里的每一列都有对应的页脚模板,就不会报错了。

(3)解决列标题旁的"T"符号

那个"T"是Material Table的排序指示器占位符,出现它是因为你给表头加了mat-sort-header,但没有正确初始化MatSort指令。你需要在组件类里完成排序的初始化:

import { MatSort } from '@angular/material/sort';
import { ViewChild } from '@angular/core';
import { MatTableDataSource } from '@angular/material/table';

// 假设你的数据源是MatTableDataSource类型
dataSource: MatTableDataSource<YourItemType>;

@ViewChild(MatSort) sort: MatSort;

ngAfterViewInit() {
  // 把sort赋值给数据源
  this.dataSource.sort = this.sort;
}

修正后的完整HTML示例(方式一)

<ng-container matColumnDef="total">
  <mat-header-cell *matHeaderCellDef mat-sort-header style="width: 15%; flex: none">Total</mat-header-cell>
  <mat-cell *matCellDef="let item" style="width: 15%; flex: none">{{item.total | currency: 'GBP'}}</mat-cell>
  <mat-footer-cell *matFooterCellDef style="width: 15%; flex: none">100</mat-footer-cell>
</ng-container>

<!-- 其他列示例 -->
<ng-container matColumnDef="name">
  <mat-header-cell *matHeaderCellDef mat-sort-header>Name</mat-header-cell>
  <mat-cell *matCellDef="let item">{{item.name}}</mat-cell>
</ng-container>

<mat-header-row *matHeaderRowDef="tableColumns"></mat-header-row>
<mat-row *matRowDef="let row; columns: tableColumns" (click)="editItem(row)"></mat-row>
<!-- 使用单独的页脚列数组 -->
<mat-footer-row *matFooterRowDef="footerColumns"></mat-footer-row>
</mat-table>

内容的提问来源于stack exchange,提问作者nick.cook

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 09:04:04