如何保存Angular Material表格中多行用户输入的全部内容
解决方案
核心思路是把输入框的值和表格数据源的对应字段做双向绑定,保存时直接读取数据源即可,具体操作如下:
步骤1:调整行数据结构
给你的表格每一行对应的数据对象新增一个用于存储输入值的字段,示例类型定义:
interface TableRowItem { // 你原有业务需要的其他字段 inputVal: string; // 新增的存储用户输入的字段,初始值设为空字符串 }
初始化数据源时,每一行数据都要带这个字段:
import { MatTableDataSource } from '@angular/material/table'; // 初始化2行示例数据 dataSourceTable = new MatTableDataSource<TableRowItem>([ { inputVal: '' }, { inputVal: '' } ]);
步骤2:修改模板绑定输入值
给input加上双向绑定,关联到当前行的inputVal字段:
<div class="mat-elevation-z8 layout-container"> <table mat-table [dataSource]="dataSourceTable"> <ng-container matColumnDef="userInput"> <th mat-header-cell *matHeaderCellDef [attr.rowspan]="2">Input</th> <td mat-cell *matCellDef="let row"> <mat-form-field class="full-width"> <!-- 核心修改:添加双向绑定 --> <input matInput [(ngModel)]="row.inputVal" /> </mat-form-field> </td> </ng-container> <!-- 你原来的其他列配置、行定义代码保持不变 --> <tr mat-header-row *matHeaderRowDef="['userInput']"></tr> <tr mat-row *matRowDef="let row; columns: ['userInput'];"></tr> </table> </div> <button mat-raised-button color="warn" (click)="saveInput()">Save</button>
步骤3:在对应模块导入FormsModule
Angular的双向绑定需要依赖FormsModule,确保在你当前组件所属的模块中已经导入:
import { NgModule } from '@angular/core'; import { FormsModule } from '@angular/forms'; // 其他导入 @NgModule({ imports: [ // 其他你已经导入的模块,比如MatTableModule、MatInputModule等 FormsModule ], // 其他配置 }) export class YourModule { }
步骤4:实现保存方法
保存时直接遍历数据源的data属性,就能拿到所有行的输入值:
saveInput() { // 提取所有用户输入的内容 const allUserInputs = this.dataSourceTable.data.map(item => item.inputVal); // 这里写你的保存逻辑,比如调用后端接口、本地存储等 console.log(allUserInputs); // 你的示例场景下会输出 ['stack', 'overflow'] }
可选方案:通过ViewChildren获取输入值
如果不想引入FormsModule使用双向绑定,可以用模板引用+ViewChildren的方式获取所有输入值:
- 模板里给input加模板引用变量:
<input matInput #rowInput />
- 组件里查询所有输入实例提取值:
import { ViewChildren, QueryList } from '@angular/core'; import { MatInput } from '@angular/material/input'; // 类属性 @ViewChildren('rowInput') rowInputs: QueryList<MatInput>; saveInput() { const allUserInputs = this.rowInputs.map(input => input.value); // 后续保存逻辑和上述方案一致 }
内容的提问来源于stack exchange,提问作者denisiulian
相关产品推荐
相关产品推荐

