【问题标题】:How do I add Validations to dynamically created FormControls?如何向动态创建的 FormControl 添加验证?
【发布时间】:2019-07-22 04:46:15
【问题描述】:

我正在创建动态 FormArray 和 FormGroups。我在其中使用 .addControl() 创建 formControl。如何为控件添加验证,这可能是必需的、电话号码、电子邮件等。

【问题讨论】:

  • 粘贴您的代码。
  • 数据可以是对象数组或单个对象 if (Array.isArray(this.resumeSections[curr].data)) { if (!this.form.get(curr)) { this. form.addControl(curr, this.fb.array([])); } const arr = this.form.get(curr) as FormArray; this.resumeSections[curr].data.forEach((datum) => arr.push(this.fb.group(datum))); } else { if (!this.form.get(curr)) { this.form.addControl(curr, this.fb.group(this.resumeSections[curr].data)); } }
  • 您可以使用 setValidators 将验证器添加到控件中。请参考此链接。 stackoverflow.com/questions/49075027/…
  • @MayuriMore,我编辑了您的问题以在您的评论中添加代码
  • 当您创建 FormControl 时,您也可以添加验证器 -this.fb.group 不仅允许添加值,还允许添加验证器。如果是 formControl,只需 this.fb.control(value,validator),如果是 formGroup,在 Angular 8 中是 this.fb.group(value,{validator:Validator}),请参阅文档 angular.io/api/forms/FormBuilder#group 并查看在控制的情况下,第二个参数是ValidatorFn | AbstractControlOptions | ValidatorFn[], asyncValidator?: AsyncValidatorFn | AsyncValidatorFn[],但在表单组中,第二个参数是AbstractControlOptions| | { [key: string]: any; } = null

标签: angular forms formbuilder form-control formgroups


【解决方案1】:

您可以使用setValidators([Validators.required]) 以及您可能想要添加的所有其他验证。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-06-11
    • 1970-01-01
    • 1970-01-01
    • 2017-05-01
    • 2013-09-18
    • 1970-01-01
    • 1970-01-01
    • 2018-02-15
    相关资源
    最近更新 更多