[英]How to append new FormGroup or FormControl to form
I have the following form
in Angular created with FormBuilder
:我在 Angular 中使用
FormBuilder
创建了以下form
:
constructor(private fb: FormBuilder) {
this.myForm = fb.group({
'name': ['', [Validators.required],
'surname': ['', [Validators.required],
'email': ['', [validateEmail]],
'address': fb.group({
'street': [''],
'housenumber': [''],
'postcode': ['']
}, { validator: fullAddressValidator })
});
}
Does exist a way to programmatically append new fields such as FormControl
or new FormGroup
to myForm
?是否存在以编程方式将新字段(例如
FormControl
或新FormGroup
到myForm
?
I mean if I want to add new fields on demand or on some conditions, how to add items to the same form that is created the first time in the constructor
?我的意思是,如果我想根据需要或在某些条件下添加新字段,如何将项目添加到第一次在
constructor
创建的同一个表单中?
You can use addControl
method of FormGroup class as per documentation您可以根据文档使用FormGroup类的
addControl
方法
So you can do as below :所以你可以做如下:
this.myForm.addControl('newcontrol',[]);
To add upon what @ranakrunal9 said.添加@ranakrunal9 所说的内容。
If you would like to use validators with addControl do the following:如果您想将验证器与 addControl 一起使用,请执行以下操作:
this.myForm.addControl('newControl', new FormControl('', Validators.required));
Just don't forget to add the following import只是不要忘记添加以下导入
import {FormControl} from "@angular/forms";
Reference to addControl: https://angular.io/api/forms/FormGroup#addControl参考 addControl: https ://angular.io/api/forms/FormGroup#addControl
Reference to FormControl: https://angular.io/api/forms/FormControl对 FormControl 的引用: https : //angular.io/api/forms/FormControl
In my opinion, you could just use an intermediate variable for this purpose.在我看来,您可以为此目的使用中间变量。 Take a look at the next example:
看下一个例子:
constructor(private fb: FormBuilder) {
let group = {
'name': ['', [Validators.required]],
'surname': ['', [Validators.required]],
'email': ['', [Validators.required]]
};
let middlename = true;
if(middlename) {
group['middlename'] = ['', [Validators.required]];
}
this.myForm = fb.group(group);
}
Also, it would a better idea to transfer a form initiation in ngOnInit hook, instead of component constructor.此外,最好在 ngOnInit 挂钩中传输表单启动,而不是组件构造函数。
我遇到了同样的问题,但由于我在主 FormGroup 中已经有一个空的 FormGroup {}
,我能够像这样附加 FormControls:
(this.myForm.get("form_group_name") as FormGroup).addControl("item1", new FormControl("default val"));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.