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

如何通过点击按钮在Angular FormArray当前项下方添加新项

在Angular FormArray指定位置插入新项的实现方法

你完全不用纠结FormArray不是普通数组的问题,Angular的FormArray本身就提供了insert()方法,专门用来在指定索引位置插入新的表单控件,完美解决你的需求。

核心实现步骤:

  1. 组件中实现addRow方法
    假设你的filterArray是FormArray类型(通常从父FormGroup中获取),点击按钮时调用insert()方法,把新的FormGroup插入到当前项的下一个位置(也就是index + 1):

    import { FormBuilder, FormArray, FormGroup } from '@angular/forms';
    
    // 组件类内代码
    constructor(private fb: FormBuilder) {}
    
    filterArray: FormArray;
    
    addRow(index: number): void {
      // 创建和现有项结构一致的新FormGroup
      const newFilterItem = this.fb.group({
        fc1: [''],
        fc2: [''],
        value: ['']
      });
      // 插入到当前点击项的紧下方(index+1位置)
      this.filterArray.insert(index + 1, newFilterItem);
    }
    
    removeRow(index: number): void {
      this.filterArray.removeAt(index);
    }
    
  2. 模板代码微调(更严谨)
    你现有的模板逻辑已经正确传递了索引,只需要把遍历对象改成filterArray.controls(FormArray的控件集合),避免潜在的遍历问题:

    <div *ngFor="let filter of filterArray.controls; let i = index" [formGroupName]="i" >
        <ng-select [items]="items1" bindLabel="name" formControlName="fc1"></ng-select>
        <ng-select [items]="items2" bindLabel="name" formControlName="fc2"></ng-select>
        <input type="text" formControlName="value" placeholder="Value">
        <button type="button" (click)="addRow(i)">Add</button>
        <button type="button" (click)="removeRow(i)"><i class="bi bi-x"></i></button>
    </div>
    

原理说明:

FormArray的insert()方法会自动维护表单控件的索引关联和变更检测,视图会因为FormArray的更新自动重新渲染,新项会立即出现在你点击的项的下方,完全符合你的需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 09:21:08