Dynamically adding required to input in template driven angular 2 form

邮差的信 提交于 2019-12-10 21:47:22

问题


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', '');

回答1:


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:


Just need to add:

[required]="isConditionIsTrue"

in your input.

You can use a condition or a boolean.

NOTE: if you are using formControls you should:

add the required control, or any other control:

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

and if you want to remove the required control, or any other control:

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



回答3:


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.

You can read this official doc



来源:https://stackoverflow.com/questions/48645671/dynamically-adding-required-to-input-in-template-driven-angular-2-form

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!