MST

星途 面试题库

面试题:Angular响应式表单中如何实现动态添加和移除表单控件

在Angular响应式表单开发中,假设你有一个表单,需要根据用户的操作动态添加或移除表单控件,例如添加新的输入框用于收集更多信息,或移除不再需要的输入框。请描述实现这一功能的基本步骤,包括如何在组件类中定义表单组和表单控件,以及如何在模板中绑定和操作这些控件。
48.6万 热度难度
前端开发Angular

知识考点

AI 面试

面试题答案

一键面试
  1. 在组件类中定义表单组和表单控件
    • 首先导入必要的模块:
      import { Component } from '@angular/core';
      import { FormGroup, FormControl, FormArray, Validators } from '@angular/forms';
      
    • 定义一个表单组:
      export class AppComponent {
        myForm: FormGroup;
        constructor() {
          this.myForm = new FormGroup({
            // 这里可以先定义一些初始的表单控件
            basicInfo: new FormControl('', Validators.required),
            dynamicControls: new FormArray([])
          });
        }
      }
      
    • 定义添加和移除表单控件的方法:
      get dynamicControls() {
        return this.myForm.get('dynamicControls') as FormArray;
      }
      
      addControl() {
        const newControl = new FormControl('', Validators.required);
        this.dynamicControls.push(newControl);
      }
      
      removeControl(index: number) {
        this.dynamicControls.removeAt(index);
      }
      
  2. 在模板中绑定和操作这些控件
    • 绑定表单:
      <form [formGroup]="myForm">
        <input type="text" formControlName="basicInfo">
        <div formArrayName="dynamicControls">
          <div *ngFor="let control of dynamicControls.controls; let i = index">
            <input type="text" [formControlName]="i">
            <button type="button" (click)="removeControl(i)">移除</button>
          </div>
        </div>
        <button type="button" (click)="addControl()">添加</button>
        <button type="submit">提交</button>
      </form>
      
    • 在上述模板中:
      • [formGroup]="myForm" 将整个表单绑定到组件类中的 myForm 表单组。
      • formControlName="basicInfo" 绑定了 myForm 中的 basicInfo 表单控件。
      • formArrayName="dynamicControls" 绑定了 myForm 中的 dynamicControls 表单数组。
      • *ngFor="let control of dynamicControls.controls; let i = index" 循环显示动态表单控件,每个控件通过 [formControlName]="i" 绑定到对应的表单控件。
      • 按钮的 (click)="removeControl(i)" 事件用于移除指定索引的动态表单控件,(click)="addControl()" 事件用于添加新的动态表单控件。