在模板驱动 angular 2 表单中动态添加输入所需的内容

Dynamically adding required to input in template driven angular 2 form

模板驱动方法: 将所需属性动态添加到 angular 2 表单中的输入字段。但是 angular 表单验证(form.valid)无法识别动态添加的必填字段。

 <input type="text"  [(ngModel)]="coumnName" name="coumnName" >

动态添加要求:

document.getElementsByName(columnName)[0].setAttribute('required', '');

In fact, once you start data binding, you are no longer working with HTML attributes. You aren't setting attributes. You are setting the properties of DOM elements, components, and directives.

你可以阅读这个official doc

您可以使用与以反应形式为 FormControl 动态设置验证器相同的技术,但使用 NgForm 指令。怎么会? angular 实际上对 NgForm 指令做了什么,它创建了 FormControl 个注册到您在表单中分配的 name 的实例。

所以您可以做的是导入 NgFormValidatorsViewChild 以引用您的表单并能够在您的组件中使用它。作为旁注,我看到您的 ngModel 变量与 name 属性相同。那行不通,它们必须是独一无二的。

所以请执行以下操作:

<form #f="ngForm">
  <input [(ngModel)]="coumnNameModel" name="coumnName" #coumnName="ngModel">
</form>

并在您的组件中,导入 NgFormViewChild,然后使用 setValidators() 并设置您想要的任何验证器,然后调用 updateValueAndValidity():

@ViewChild('f') myForm: NgForm;

// when you want to set required validator:
setRequired() {
  this.myForm.form.get('coumnName').setValidators([Validators.required])
  this.myForm.form.get('coumnName').updateValueAndValidity();
}

StackBlitz

只需添加:

[required]="isConditionIsTrue"

在您的输入中。

您可以使用条件或布尔值。

注意:如果您正在使用 formControls,您应该d:

添加所需的控件或任何其他控件:

this.form.addControl('formControlName', new FormControl(ValueToSet, Validators.required));

如果您想删除所需的控件或任何其他控件:

this.form.get('formControlName').reset();
this.form.removeControl('formControlName');