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

Angular Mat Table编辑行值存入TS变量时出现undefined问题求助

Fixing Undefined Value on Mat Table Update

Hey there! I see you're having trouble getting the updated data from your Mat Table when clicking the Update button—let's fix that right away.

The Root Cause

In your update() method, you're trying to access this.value, but you never defined this variable anywhere! The edits you make are actually directly modifying the elements in your dataSource, so you need to pull the updated values from there instead.

Step-by-Step Solution

  1. Access the Updated Data from dataSource
    Your dataSource holds all the table data, including the edits you've made. In your update() method, you can get the full updated dataset by accessing this.dataSource.data.

  2. Modify the update() Method
    Here's how to adjust your TypeScript code to capture the updated data:

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

// Define an interface for your table data type
interface TableItem {
  key: string;
  value: string;
  editable: boolean;
}

@Component({
  selector: 'app-approval',
  templateUrl: './approval.component.html',
  styleUrls: ['./approval.component.css']
})
export class ApprovalComponent {
  displayedColumns: string[] = ['key', 'value', 'actions'];
  // Initialize your data source with your actual data
  dataSource = new MatTableDataSource<TableItem>([
    { key: 'Sample Key 1', value: 'Sample Value 1', editable: false },
    { key: 'Sample Key 2', value: 'Sample Value 2', editable: false }
  ]);

  edit(e: TableItem) {
    e.editable = !e.editable;
  }

  update() {
    // Get the full updated dataset from the data source
    const updatedTableData = this.dataSource.data;
    console.log('Updated Table Data:', updatedTableData);

    // If you want to extract just the key-value pairs (without the editable flag)
    const keyValuePairs = updatedTableData.map(item => ({
      key: item.key,
      value: item.value
    }));
    console.log('Key-Value Pairs:', keyValuePairs);
  }
}
  1. Confirm Template Binding is Correct
    Your template's [(ngModel)]="element.value" is already properly binding to each item's value in the data source—this keeps dataSource updated in real-time as you edit, so no changes are needed here.

Quick Template Improvement

I noticed your value column header says "No."—you might want to update that to "Value" for clarity:

<ng-container matColumnDef="value" >
  <th mat-header-cell *matHeaderCellDef> Value </th>
  <!-- Rest of the column code -->
</ng-container>

Now when you click the Update button, you'll see the full updated dataset in your console instead of undefined!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.07 06:47:36