Wednesday 26 December 2018

How to dynamically add and remove the validators from angular reactive forms?

For the Angular Developer most of the computer and learner want to know how to dynamically add and remove the validation in reactive Forms:

So the Angular provide the 3 set of the methods which can be used for this.

1. setValidators()
2. clearValidators()
3. updateValueAndValidity()


setValidators: setting the validation on the control on which you want to apply on this

clearValidators: If user want to remove the existing validations from the control then he
can use this method.

updateValueAndValidity: this method is always use when you set or clear the validation in
angular reactive forms.

for applying all the above method first we find the control in our typescript file by
following way

suppose on my component here is the HTML part of the phone control

<label class="radio-inline">
<input type="radio" value="phone" (click)="onContactPreferenceChange('phone')" formControlName="contactPreference" >Phone
</label>

Now on the ts file we will find the phone control by following way
const phoneControl = this.employeeForm.get('phone');

after this according to our need we can add or clear the validation from the control.

No comments:

Post a Comment

AdSense

The Ultimate Guide to Interceptors: Understanding Their Power and Functionality

  The Ultimate Guide to Interceptors: Understanding Their Power and Functionality An interceptor is a service that can intercept HTTP reques...

Follow