相关疑难解决方法(0)

Angular - 反应式表单 - 如何使用类和验证器将对象传递到 FormGroup

我要创建一个大型表单,并决定使用反应式表单功能以方便使用。然而,我面临着一些可能显而易见的挑战并寻求帮助。

下面是两种情况,除了验证之外,它们产生相同的结果。该createFormWithValidation()方法指定了每个控件及其关联的验证器。该方法仅使用对象但不添加验证器createFromPassingObject()来创建相同的表单。this.party

我的目标是将一个对象传递给this.fb.group()该对象,该对象将具有属于该类的控件,并且能够为该类的每个属性指定验证器Party

// 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 …
Run Code Online (Sandbox Code Playgroud)

angular2-formbuilder angular angular-reactive-forms

5
推荐指数
1
解决办法
1万
查看次数