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

使用数组作为Material DataTable的dataSource报错:this.dataSource.connect不是函数

嘿,这个问题我太熟了!你碰到的 ERROR TypeError: this.dataSource.connect is not a function,本质是因为Angular Material的MatTable不能直接把普通数组当作dataSource来用——它要求的数据源必须是实现了DataSource接口的对象,而普通数组压根没有connect()这个方法,所以才会触发这个报错。

下面给你一步步的解决方案:

1. 先导入MatTableDataSource

在你的组件TS文件顶部,先引入Material提供的数据源包装类:

import { MatTableDataSource } from '@angular/material/table';

2. 把普通数组包装成合规的数据源

在组件类里,将你的原始数组用MatTableDataSource包裹起来:

// 假设这是你原本想用的数组
originalDataArray: any[] = [
  { id: 1, name: '示例1' },
  { id: 2, name: '示例2' }
];

// 包装成MatTable能识别的数据源
dataSource = new MatTableDataSource(this.originalDataArray);

如果你的数组是动态加载的(比如从后端API获取),记得在数据更新后同步更新数据源:

// 比如API请求完成后更新数据
this.dataService.fetchData().subscribe(res => {
  this.originalDataArray = res;
  // 直接更新数据源的data属性,或者重新实例化都可以
  this.dataSource.data = this.originalDataArray;
});

3. 模板里直接用包装后的数据源

你的HTML模板不需要改动太多,直接使用包装好的dataSource即可:

<table mat-table [dataSource]="dataSource">
  <!-- 列定义示例 -->
  <ng-container matColumnDef="id">
    <th mat-header-cell *matHeaderCellDef> ID </th>
    <td mat-cell *matCellDef="let item"> {{item.id}} </td>
  </ng-container>

  <ng-container matColumnDef="name">
    <th mat-header-cell *matHeaderCellDef> 名称 </th>
    <td mat-cell *matCellDef="let item"> {{item.name}} </td>
  </ng-container>

  <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
  <tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
</table>

额外提一句:MatTableDataSource还内置了过滤、排序、分页这些常用功能,直接调用对应的方法就行,比如添加过滤功能:

applyFilter(filterValue: string) {
  this.dataSource.filter = filterValue.trim().toLowerCase();
}

内容的提问来源于stack exchange,提问作者Hamza Haddad

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 07:07:52