0

I have a form in which based on a condition i need to disable the required validator from the form control. My current code looks like this.

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

this.dealForm.get('address').clearValidators();
this.dealForm.get('address').setValidators();
this.dealForm.get('address').updateValueAndValidity();

From this piece of code this form control still has the required validator. Does anybody have any suggestion regarding my issue ? Followed suggestions from another topic, the required validator still present and form is invalid

Thank for your help guys, your answers were working. I had a problem with the way I was accessing the form data.

5
  • setValidators() expects at least one argument... :). Your code will not run. Though you only need clearValidators() to remove the validators, no need to use updateValueAndValidity() after. Commented Sep 3, 2018 at 9:38
  • @Vikas followed the instructions from there, not working in my case Commented Sep 3, 2018 at 9:45
  • 1
    this.dealForm.get('address').setValidators(null); if this does not work pls provide a stackblitz Commented Sep 3, 2018 at 9:57
  • @Teodor Check This StackBlitz I am unable to reproduce the same Commented Sep 3, 2018 at 11:44
  • @Vikas thank you for the help. I find the answer by the way. It was my mistake from the beginning :( Commented Sep 3, 2018 at 12:17

2 Answers 2

2

after clear don't again call setValidators

use like this,

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

this.dealForm.get('address').clearValidators();
this.dealForm.get('address').updateValueAndValidity();
Sign up to request clarification or add additional context in comments.

2 Comments

tried it, still not working. the required attribute is still present thus making the form invalid.
can you create stackblitz demo.. so i can help you
0

Try something like this:

address: new FormControl('', [Validators.required])

this.dealForm.get('address').clearValidators();

this.dealForm.get('address').updateValueAndValidity();

I also suggest you to use required validation in template only like:

<input type="text" required>

In this case when html will be loaded than validation will be considered.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.