Angular - 响应式表单 - 如何使用 class 和验证器将对象传递给 FormGroup

Angular - Reactive Forms - How to pass an object to a FormGroup with a class and validators

我要创建一个大表单,因此决定使用反应式表单功能以方便使用。但是,我面临着一些可能很明显的挑战并正在寻求帮助。

下面是两个产生相同结果但验证除外的案例。 createFormWithValidation() 方法指定每个控件及其关联的验证器。 createFromPassingObject() 方法仅使用 this.party 对象创建相同的表单,但没有添加验证器。

我的目标是将对象传递给 this.fb.group(),该对象将具有属于 class 的控件,并且能够为 [=] 的每个 属性 指定验证器17=] 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));

希望我说得有道理。