如何验证动态控件

时间:2019-08-11 05:44:22

标签: angular angular-forms

我在Angular的form标记中有一个表。有一个文本框和一个下拉列表。我想验证它们(如果用户未输入值或未选择下拉菜单,则显示错误消息)。当用户单击下拉列表时,将基于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
}

enter image description here

1 个答案:

答案 0 :(得分:0)

希望...这就是您所期望的。请通过stackblitz进行检查。 Dynamically changing form group with validation