1

I need to programmatically change the validators of an input in a Angular Reactive Form.

So I init the form:

...
limitNumber: [{ value: null, disabled: (this.id ? true : false) }]
...

And later on I enable the input and change its validators to be required:

this.newEventForm.get('limitNumber').enable();
this.newEventForm.get('limitNumber').setValidators(Validators.required);

Right after this, the state of the input is VALID as long as it stays pristine. If I edit the input value and erase then it becomes 'INVALID'.

My problem is that I need the input to be invalid as soon as I set its validators to required even if pristine.

How can I do ?

***** EDIT *****

My goal is to be able to make an input to be required conditionally. Imagine the user creates an event. In the new event form it can choose to set a maximum number of participants. If the user toggles the input (lets call it 'isLimited') then I need a new input, to enter this numerical limit, which gets enabled (lets call it 'limitNumber' input) which hence must be filled.

So my ultimate goal is to make this input "required" only if the 'isLimited' input is toggled true

3
  • why do you need such a feature what is the ulitmate goal here , may be there is another easy way. Commented Aug 7, 2017 at 16:47
  • you need to get that formControl and then mark it as touched that might help like this this.formControl.control.markAsUntouched({onlySelf: true}); Commented Aug 7, 2017 at 16:49
  • @RahulSingh I tried Untouched, Touched and Dirty without success. See my edit in my post which explains the ultimate goal. Hope it's more clear Commented Aug 7, 2017 at 17:31

1 Answer 1

1

I just had to use the following code to check validity:

this.newEventForm.get('limitNumber').updateValueAndValidity();
Sign up to request clarification or add additional context in comments.

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.