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

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

问题描述

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

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" >

动态添加:

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

推荐答案

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

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.

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

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.

请执行以下操作:

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

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

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();
}

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

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