我要创建一个大型表单,并决定使用反应式表单功能以方便使用。然而,我面临着一些可能显而易见的挑战并寻求帮助。
下面是两种情况,除了验证之外,它们产生相同的结果。这createFormWithValidation()
方法指定每个控件及其关联的验证器。这createFromPassingObject()
方法仅使用this.party
对象但没有添加验证器。
我的目标是将一个对象传递给this.fb.group()
它将具有属于该类的一部分的控件,并且能够为该类的每个属性指定验证器Party
Class.
// The Class with the properties
export class Party {
firstName: string = '';
lastName: string = '';
constructor() {}
}
// party Object
myForm: FormGroup;
this.party = new Party();
// Form with explicit controls and their validators
createFormWithValidation() {
this.myForm = this.fb.group({
firstName: [this.party.firstName, [Validators.required, Validators.minLength(3)]],
lastName: [this.party.lastName, [Validators.required, Validators.minLength(3)]]
})
}
// The goal is to achieve this type of method where this.party will be the object of the controls and their validators.
createFormPassingObject() {
this.myForm = this.fb.group(this.party)
}
非常感谢您的帮助。
这就是我正在为我的案例做的事情。请注意,我也正在开发我的项目,因此不能保证它能够正常工作。无论如何,我就是这样做的:
// First is to define a const that is going to be the pre-defined object going in this.formBuilder.group()
export const predefinedFormGroup = {
property1: new FormControl('', Validators go here),
property2: new FormControl('', Validators go here)
}
// Create the form
this.myForm = this.formBuilder.group(predefinedFormGroup);
// My use-case is I have to add new FormGroup to an existed FormGroup in an existed Form:
(<FormGroup>this.myForm.get['sections']).addControl(section.name, this.formBuilder.group(section.interface));
我希望我在这里说得有道理。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)