Angular的ReactiveForms库提供了FormArray类,用于管理表单中的数组控件。FormArray类提供了removeAt()方法,用于移除指定索引处的控件。
要移除FormArray中的所有元素,可以使用循环遍历FormArray的长度,并在每个索引处调用removeAt()方法来逐个移除元素。以下是一个示例代码:
import { Component } from '@angular/core';
import { FormArray, FormBuilder } from '@angular/forms';
@Component({
selector: 'app-form-array-example',
template: `
`
})
export class FormArrayExampleComponent {
myForm = this.fb.group({
myArray: this.fb.array([
this.fb.control('Value 1'),
this.fb.control('Value 2'),
this.fb.control('Value 3')
])
});
constructor(private fb: FormBuilder) {}
removeAll() {
const formArray = this.myForm.get('myArray') as FormArray;
while (formArray.length !== 0) {
formArray.removeAt(0);
}
}
}
在上面的示例中,我们在模板中使用*ngFor指令遍历FormArray中的控件,并使用removeAll()方法来移除所有元素。在removeAll()方法中,我们首先获取FormArray的引用,并使用while循环来逐个移除控件,直到FormArray的长度为0。
请注意,要使用FormArray类,您需要引入@angular/forms
库,并确保在组件的构造函数中注入FormBuilder。
上一篇:Angular ReactiveForms - 如何将验证器设置为整个 FormGroup
下一篇:Angular ReactiveForms:ControlValueAccessor 在不通知更改的情况下验证初始值。