Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove required field if the field is hidden state - Angular 2

I need a solution for below mentioned issue. Kindly help to solve the problem.

Case 1:

Password is a required field only for new user Creation.

Password: new FormControl('', Validators.required),

Case 2:

Changing the password visibility hidden using *ngIf

( "ng-reflect-ng-if":"false" )

Case 3 :

Now If i hit on Save its says Password required. help me to fix this issue field should not validate if it is hidden .

Thanks.

like image 483
Karthick Venkat Avatar asked Oct 26 '17 10:10

Karthick Venkat


1 Answers

You can use clearValidators() and setValidators(), so whatever boolean flag you have for your hidden field, here I use hidden, and when that flag is true, the field is hidden.

You can do the following when you toggle that value:

this.hidden = !this.hidden
this.hidden ? this.myForm.get('Password').clearValidators() : 
              this.myForm.get('Password').setValidators([Validators.required])
this.myForm.get('Password').updateValueAndValidity();

DEMO: https://plnkr.co/edit/Jf2iTy5y3NMDNi5IDyoI?p=preview

like image 99
AT82 Avatar answered Oct 16 '22 03:10

AT82