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

Angular报错:Cannot read properties of undefined (reading 'data') 求助

Angular TypeError: Cannot read properties of undefined (reading 'data') 问题分析

报错直接原因

报错指向oviewer.component.ts:97:37,也就是isAllSelected()方法中this.dataSource.data.length这一行——this.dataSource为undefined,无法读取其data属性。

具体触发场景

  1. 组件初始化阶段,dataSource还未被赋值(比如数据是异步请求获取的,请求完成前dataSource是undefined),但模板中的mat-checkbox绑定了isAllSelected()方法,会立即调用该方法。
  2. 代码中存在拼写错误,间接加剧了问题:
    • 方法名iSAllSelected()大小写错误(应该是isAllSelected),导致模板调用的isAllSelected()可能未正确关联到方法。
    • 模板中[indeterminate]-"selection.hasValue() && lisAllSelected()"里的lisAllSelected()是拼写错误,应为!isAllSelected(),同时绑定符号写错(-应为=)。
    • checkboxLabel()方法内部调用isAllSelected(),同样会触发空值访问错误。

解决方案

1. 初始化dataSource

在组件类中给dataSource设置初始值,避免其为undefined:

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

// 组件类内
dataSource = new MatTableDataSource<any>([]); // 初始化为空的数据源
selection = new SelectionModel<any>(true, []); // 确保多选模型也完成初始化

2. 给dataSource访问添加空值保护

修改isAllSelected()和toggleAllRows()方法,使用可选链操作符?.防止空值访问:

isAllSelected() {
  const numSelected = this.selection.selected.length;
  const numRows = this.dataSource?.data?.length || 0; // 空值时默认取0
  return numSelected === numRows;
}

toggleAllRows() {
  if (this.isAllSelected()) {
    this.selection.clear();
    return;
  }
  // 给dataSource.data加空值保护,避免展开undefined报错
  this.selection.select(...(this.dataSource?.data || []));
}

3. 修正拼写与语法错误

  • 把方法名iSAllSelected()改为isAllSelected()(保持大小写一致)。
  • 修正模板中的拼写与绑定错误:
<mat-checkbox
  (change)="$event ? toggleAllRows() : null" color="primary"
  [checked]="selection.hasValue() && isAllSelected()"
  [indeterminate]="selection.hasValue() && !isAllSelected()"
  [aria-label]="checkboxLabel()"
></mat-checkbox>

4. 完善checkboxLabel()方法

确保方法完整闭合,避免语法错误:

checkboxLabel(row?: any): string {
  if (!row) {
    return `${this.isAllSelected() ? 'deselect' : 'select'} all`;
  }
  // 补充row存在时的逻辑示例
  return `${this.selection.isSelected(row) ? 'deselect' : 'select'} row`;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 13:01:54