如何在Angular中动态添加FormControl到FormGroup?
例如,我想添加一个名称为“new”的必填控件,其默认值为''。
如何在Angular中动态添加FormControl到FormGroup?
例如,我想添加一个名称为“new”的必填控件,其默认值为''。
addControl
是你所需要的。请注意第二个参数必须是一个像这样的 FormControl 实例:
this.testForm.addControl('new', new FormControl('', Validators.required));
如果需要,您还可以使用setValidators
方法动态添加验证器。调用此方法会覆盖任何现有的同步验证器。
this.testForm.addControl('name', new FormControl('', [Validators.required, Validators.max(5)]))
- A.CasanovaFormBuilder
创建表单,您也可以使用它来添加控件:constructor(private fb: FormBuilder) { }
method() {
this.testForm.addControl('new', this.fb.control('', Validators.required));
}
简单使用:
this.testForm.addControl('new', this.fb.group({
name: ['', Validators.required]
}));
Angular 14为表单添加了类型。以下是新语法的样子:
表单声明
public form = new FormGroup<{ new?: FormControl<string | null> }>();
new
控件必须声明为可选项。如果未首先声明该字段,则无法使用 addControl
。interface MyForm {
field1: FormControl<string | null>;
field2: FormControl<string | null>;
new?: FormControl<string | null>;
}
public form = new FormGroup<MyForm>({
field1: new FormControl<string | null>('', Validators.required),
field2: new FormControl<string | null>('', Validators.required),
});
在表单中添加控件
this.form.addControl('new', new FormControl<string | null>('', Validators.required));
import { FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms';
@Component({
selector: 'app-component-name',
templateUrl: './component-name.component.html',
styleUrls: ['./component-name.component.scss']
})
export class ComponentName implements OnInit {
formGroup: FormGroup;
constructor(private formBuilder: FormBuilder) {}
ngOnInit() {
this.formGroup = this.formBuilder.group({
firstName: new FormControl('', Validators.required),
lastName: new FormControl('', Validators.required),
});
}
// Add single or multiple controls here
addNewControls(): void {
this.formGroup = this.formBuilder.group({
...this.formGroup.controls,
email: ['', Validators.required],
phone: ['', Validators.required]
});
}
}
我在 Angular 12 中遇到了同样的问题。以下代码片段对我完美地起作用。
声明表单:
public form: FormGroup;
为表单创建一个新的控件:
this.form.addControl('new', new FormControl('', Validators.required));
要动态地向现有的FormArray
实例中添加一个新的FormControl
,可以使用强制转换技术。
form: FormGroup;
constructor(private fb: FormBuilder){
this.form = this.fb.group({
formArrayName: this.fb.array([])
});
} //
addNewFormArrayInstance(insertIndex: number){
// insertIndex to insert at a specific position
const NEWFORMGROUP = new FormGroup({
'control1': new FormControl(''),
'control2': new FormControl({value: [], disabled: true}),
'control3': new FormControl('', Validators.required),
'control4': new FormControl(true)
});
// use push(NEWFORMGROUP) if needed
(<FormArray>this.form.get('formArrayName')).insert(insertIndex, NEWFORMGROUP);
} //
addControlToFormArrayInstance(index: number){
// index is the FormArray instance's index to which a new control is to be added
(<FormGroup>
(<FormArray>this.form.get('formArrayName')).controls[index]
).addControls(
'newControl', new FormControl('new')
);
} //