面试题答案
一键面试- 在组件类中定义表单组和表单控件:
- 首先导入必要的模块:
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); }
- 首先导入必要的模块:
- 在模板中绑定和操作这些控件:
- 绑定表单:
<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()"
事件用于添加新的动态表单控件。
- 绑定表单: