角-响应式表单-如何使用类和验证器将对象传递给FormGroup [英] Angular - Reactive Forms - How to pass an object to a FormGroup with a class and validators

查看:98
本文介绍了角-响应式表单-如何使用类和验证器将对象传递给FormGroup的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个很大的表格要创建,因此决定使用反应式表格功能以便于使用。但是,我面临着一些显而易见的挑战,正在寻求帮助。

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.

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

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.

我的目标是将对象传递给 this.fb.group()类的一部分,并能够为 Party 类的每个属性指定验证器。

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)
}

非常感谢您的帮助。

推荐答案

这是我正在为案件做的事情。请注意,我也正在从事我的项目,因此不能保证它会正常工作。无论如何,这就是我的方法:

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.

这篇关于角-响应式表单-如何使用类和验证器将对象传递给FormGroup的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆