【问题标题】:Angular - Reactive Forms - How to pass an object to a FormGroup with a class and validatorsAngular - 反应式表单 - 如何使用类和验证器将对象传递给 FormGroup
【发布时间】:2018-05-14 13:25:28
【问题描述】:

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

以下是两种产生相同结果的情况,但验证除外。 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 object of the controls and their validators. 

createFormPassingObject() {
  this.myForm = this.fb.group(this.party)
}

非常感谢您的帮助。

【问题讨论】:

    标签: angular angular-reactive-forms angular2-formbuilder


    【解决方案1】:

    这就是我正在为我的案子做的事情。请注意,我也正在处理我的项目,因此无法保证它会正常工作并且会正常工作。无论如何,这就是我的做法:

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

    我希望我在这里说得通。

    【讨论】:

    • 好的,所以你的建议是创建另一个对象来保存我的数据类除了验证器。由于数据类属性本质上是 from 组的属性,我认为必须有一种方法可以以通用方式执行此操作。有什么想法吗?
    • 基本上是的,你必须传入一个 OBJECT。据我了解,您的 this.party 不是 OBJECT 而是 Party 类的实例。我想如果你想要这些类属性的值,你可以这样做:this.myForm.addControl('name of control', this.formBuilder.control(this.party.firstName, Validators go here)); 但我在想你如何循环一个类的​​实例来获取所有属性来为你的myForm 创建适当的控件。
    • 我只是想不出一种方法来使其通用,因为您的验证器将特定于数据类中的每个属性。在这种情况下,我无法弄清楚如何创建一个接收数据类的函数并确定哪些验证器属于每个类。听起来最好的选择是创建每个组中的所有属性,而不是在this.fb.group() 上中继,因为确定 OBJECT(正如您之前指出的)的工作在每个实现中必须是唯一的。跨度>
    • 我正在寻找相同的,我希望能够从一个表示数据库表(模型)的类创建一个 FormGroup,所以我会写 this.myForm =新表单组(class_instance);但我不知道这是否可能以及如何做到这一点。
    猜你喜欢
    • 1970-01-01
    • 2019-05-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-05
    • 1970-01-01
    相关资源
    最近更新 更多