【问题标题】:Make fields required using array in angular form control?使用角度表单控件中的数组制作所需的字段?
【发布时间】:2021-10-26 19:34:30
【问题描述】:

我在Angular 中有一个表单,其中我使用了两个数组(有 4 个字段)作为控件。
用户可以单击+ 图标为任何数组添加更多索引并填充值。

如何使该数组的字段required。每当我检查控件是否为空时,每次都显示数组中有空索引。
如何判断是否为空?

【问题讨论】:

标签: angular forms frontend formgroups


【解决方案1】:

如果您使用的是响应式表单(而不是模板驱动的表单),您可以以编程方式将任何类型的 AbstractControl 添加到您的表单中。

假设点击 + 调用一个方法,您可以让它创建一个新的 FormGroup 并将其推送到您的 FormArray(再次假设这是您的表单的结构):

public addIndexToArray() {
  const formGroup = new FormGroup({
    index: new FormControl(null, [Validators.required])
    // any other fields
  })
  this.myFormArray.push(formGroup)
}

现在index FormControl 将在用户触摸 FormControl 但未输入值时被标记为无效。 Validators 是原生 Angular FormsModule 的一部分,它提供了许多有用的工具。

【讨论】:

    猜你喜欢
    • 2022-01-05
    • 2019-07-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-26
    • 2017-06-03
    • 1970-01-01
    • 2017-05-21
    相关资源
    最近更新 更多