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

╄→гoц情女王★ 提交于 2019-12-21 19:59:46

问题


I have a large form to create and decided to use the reactive form feature for ease of use. However, I am facing a few challenges that might be obvious and looking for help.

Below are two cases that yield the same outcome with the exception of the validation. The createFormWithValidation() method specifics every control and it's associated validators. The createFromPassingObject() method creates the same form using just the this.party object but without the added validators.

My goal is to pass an object to this.fb.group() that will have the controls that are part of the class and be able to specify validators for each property of the 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)
}

Your help is greatly appreciated.


回答1:


Here's what I am doing for my case. Be aware that I am in the midst of working on my project as well so there's no guarantee that it will work and it will work properly. Anyway, this is how I do it:

// 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));

I hope I am making sense here.



来源:https://stackoverflow.com/questions/47576455/angular-reactive-forms-how-to-pass-an-object-to-a-formgroup-with-a-class-and

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!