Angular中如何获取表格输入值并生成键值对JSON
解决带Row Span的动态表格Reactive Form取值问题
问题分析
你的场景是构建带跨行(rowspan)的动态输入表格,包含username和email字段,需要点击按钮后通过Reactive Form收集所有输入值,生成以username为键、对应邮箱列表为值的JSON结构。核心问题在于动态表格的表单控件结构未与DOM正确绑定,导致无法正常获取输入值。
解决方案实现
1. 调整表单结构
使用FormArray嵌套FormGroup,每个跨行的username对应一组email输入框,表单结构设计如下:
import { Component, OnInit } from '@angular/core'; import { FormBuilder, FormGroup, FormArray } from '@angular/forms'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent implements OnInit { userForm: FormGroup; constructor(private fb: FormBuilder) { this.userForm = this.fb.group({ users: this.fb.array([]) }); } ngOnInit(): void { // 初始化示例数据,可根据业务需求动态添加用户条目 this.addUserWithEmails(['email1@test.com', 'email2@test.com']); this.addUserWithEmails(['email3@test.com']); } get users(): FormArray { return this.userForm.get('users') as FormArray; } addUserWithEmails(emails: string[]): void { const userGroup = this.fb.group({ username: [''], emails: this.fb.array(emails.map(email => this.fb.control(email))) }); this.users.push(userGroup); } getTableValue(): void { const formValue = this.userForm.value; const result: { [key: string]: string[] } = {}; formValue.users.forEach((user: any) => { if (user.username) { // 过滤空邮箱值 result[user.username] = user.emails.filter((email: string) => email); } }); console.log(JSON.stringify(result, null, 2)); } }
2. 模板绑定调整
确保模板中表单控件与FormArray、FormGroup正确关联,适配rowspan布局:
<form [formGroup]="userForm"> <table border="1"> <thead> <tr> <th>Username</th> <th>Email</th> </tr> </thead> <tbody formArrayName="users"> <tr *ngFor="let user of users.controls; let i = index" [formGroupName]="i"> <td [rowspan]="user.get('emails')?.length || 1"> <input formControlName="username" placeholder="Enter username"> </td> <td *ngFor="let email of user.get('emails')?.controls; let j = index" [formArrayName]="'emails'"> <input [formControlName]="j" placeholder="Enter email"> </td> </tr> </tbody> </table> <button type="button" (click)="getTableValue()">getTableValue</button> </form>
3. 关键说明
- 每个用户条目是独立的
FormGroup,包含username单行控件和emails数组控件,完美匹配跨行布局 - 通过
formArrayName、formGroupName、formControlName三层绑定,确保DOM元素与表单数据模型同步 getTableValue方法中遍历表单值,过滤空输入后生成符合要求的JSON结构
内容的提问来源于stack exchange,提问作者Madpop
相关产品推荐
相关产品推荐

