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

Angular中如何根据输入数量动态添加表单行

实现Angular表单根据数量动态添加输入行

问题描述

开发Angular表单时,需要实现输入数量(qty)后,动态生成对应行数的表单输入行,现有部分代码如下:

<table formArrayName="displayArray">
  <thead>
    <tr>
      <th></th>
    </tr>
  </thead>
</table>
<tbody>
  <tr *ngFor="let displayArray of displayArray.controls; let i = index;" [formGroupName]="i">
    <td>
      <input type="text" formCOntrol="DisplayRow" class="form-control" style="width:700px">
    </td>
  </tr>
</tbody>
this.serialForm = this.fb.group({
  id: [0],
  qty: [''],
  displayArray: this.fb.array([{
    DisplayRow:['']
  }])
})

get displayArray():FormArray{
  return this.serialForm.get('displayArray') as FormArray;
}

解决方案

1. 修正HTML结构错误

原代码存在两处关键错误:

  • <tbody>标签未包含在<table>内部
  • formCOntrol拼写错误,应为formControlName

修正后的HTML:

<!-- 数量输入框 -->
<div class="mb-3">
  <label>数量:</label>
  <input type="number" formControlName="qty" (input)="updateDisplayArray()" class="form-control">
</div>

<!-- 动态表单行表格 -->
<table formArrayName="displayArray" class="table">
  <thead>
    <tr>
      <th>输入内容</th>
    </tr>
  </thead>
  <tbody>
    <tr *ngFor="let row of displayArray.controls; let i = index;" [formGroupName]="i">
      <td>
        <input type="text" formControlName="DisplayRow" class="form-control" style="width:700px">
      </td>
    </tr>
  </tbody>
</table>

2. 编写动态更新FormArray的方法

在组件类中实现updateDisplayArray方法,根据qty的值添加/移除表单行:

updateDisplayArray(): void {
  // 获取输入的数量,转为数字(默认0)
  const targetQty = Number(this.serialForm.get('qty')?.value) || 0;
  const currentRowCount = this.displayArray.length;

  // 增加行数:当目标数量大于现有行数时,补充新的表单组
  if (targetQty > currentRowCount) {
    for (let i = currentRowCount; i < targetQty; i++) {
      this.displayArray.push(this.fb.group({
        DisplayRow: ['']
      }));
    }
  } 
  // 减少行数:当目标数量小于现有行数时,移除多余的表单组
  else if (targetQty < currentRowCount) {
    // 从目标数量位置开始,移除多余的行
    this.displayArray.removeAt(targetQty, currentRowCount - targetQty);
  }
}

3. 初始化与完善组件逻辑

调整表单初始化逻辑,并在组件加载时触发一次更新方法:

import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, FormArray } from '@angular/forms';

@Component({
  selector: 'app-your-component',
  templateUrl: './your-component.component.html',
})
export class YourComponent implements OnInit {
  serialForm!: FormGroup;

  constructor(private fb: FormBuilder) {}

  ngOnInit(): void {
    this.serialForm = this.fb.group({
      id: [0],
      qty: [''],
      displayArray: this.fb.array([]) // 初始化为空数组,后续动态生成
    });
    // 页面加载时根据初始qty生成行
    this.updateDisplayArray();
  }

  get displayArray(): FormArray {
    return this.serialForm.get('displayArray') as FormArray;
  }

  updateDisplayArray(): void {
    const targetQty = Number(this.serialForm.get('qty')?.value) || 0;
    const currentRowCount = this.displayArray.length;

    if (targetQty > currentRowCount) {
      for (let i = currentRowCount; i < targetQty; i++) {
        this.displayArray.push(this.fb.group({
          DisplayRow: ['']
        }));
      }
    } else if (targetQty < currentRowCount) {
      this.displayArray.removeAt(targetQty, currentRowCount - targetQty);
    }
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 10:27:46