Angular Mat Table编辑行值存入TS变量时出现undefined问题求助
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
Access the Updated Data from
dataSource
YourdataSourceholds all the table data, including the edits you've made. In yourupdate()method, you can get the full updated dataset by accessingthis.dataSource.data.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); } }
- 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 keepsdataSourceupdated 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

