动态添加需要以模板驱动的角度2形式输入 [英] Dynamically adding required to input in template driven angular 2 form

查看:43
本文介绍了动态添加需要以模板驱动的角度2形式输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

模板驱动的方法::将所需的属性动态添加到以角度2格式输入的输入中.但是角度形式验证(form.valid)无法识别动态添加的必填字段.

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

动态添加必需项:

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

解决方案

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

因此,您可以做的是导入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

Template driven approach: Dynamically adding required attribute to input filed in angular 2 form. But the angular form validation(form.valid) not recognizing the dynamically added required field.

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

Adding dynamically required:

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

解决方案

You can use the same technique as setting a validator dynamically for a FormControl in a reactive form, but using the NgForm directive. How come? What angular actually does with the NgForm directive it creates FormControl instances registered to the name you assign in your form.

So what you can do, is import NgForm, Validators and ViewChild to reference your form and be able to use it in your component. As a side note, I see that your ngModel variable is the same as the name attribute. That won't work, they need to be unique.

So do the following:

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

and in your component, import NgForm and ViewChild and then use setValidators() and set whatever validators you want, then call 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

这篇关于动态添加需要以模板驱动的角度2形式输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆