【问题标题】:How to validate dynamic controls如何验证动态控件
【发布时间】:2019-08-11 05:44:22
【问题描述】:

我在 Angular 的表单标签中有一个表格。有一个文本框和一个下拉菜单。我想验证它们(如果用户未输入值或未选择下拉菜单,则显示错误消息)。当用户单击下拉列表时,动态输入字段将基于 API 生成。我为输入文本框和下拉菜单创建了表单控件。我无法验证这些动态输入字段,如何添加它们进行验证?这是我尝试过的。

this.customTableForm = new FormGroup({
  // created for static inputs
  'impName': new FormControl(null, Validators.required),
  'tablelistDropdown': new FormControl(null, Validators.required),
});

tableChanged(){
  // dynamic table values are coming from here
  this.importerService.listColumnData(this.selectedTable).subscribe(result => {
    this.columns = result['data'].columns;
  });
}

// Validations for input text and dropdown
get hasTableListDropDownError() {
  return (
    this.customTableForm.get('tablelistDropdown').touched &&
    this.customTableForm.get('tablelistDropdown').errors &&
    this.customTableForm.get('tablelistDropdown').errors.required
  )
}

get hasInputTextBoxErrorRequired() {
  const controller = this.customTableForm.get('impName');
  return controller.touched && controller.errors && controller.errors.required
}

【问题讨论】:

  • 每一行都有输入和下拉?
  • 动态表单只有名称(标签)和输入文本。假设如果您从下拉菜单中单击 item1,它将生成 5 个输入框和标签。单击下拉菜单 2 时,将显示 3 个输入框和标签。
  • 由于它在选择时动态输入,您应该更新验证。在订阅中 this.customTableForm.get('impName').updateValueAndValidity()
  • 我不需要为此创建自定义控件吗?我是新人
  • 你应该使用formGroupArray...尝试找出什么是formGroupArray。我会尽快更新

标签: angular angular-forms


【解决方案1】:

希望...这是您所期望的。请在 stackblitz 中查看。 Dynamically changing form group with validation

【讨论】:

    猜你喜欢
    • 2015-11-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多