Manuel RODRIGUEZ
Manuel RODRIGUEZ

Reputation: 2161

Angular reactive forms input is valid if pristine even if setValidators set to required

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

Upvotes: 1

Views: 2912

Answers (1)

Manuel RODRIGUEZ
Manuel RODRIGUEZ

Reputation: 2161

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

this.newEventForm.get('limitNumber').updateValueAndValidity();

Upvotes: 1

Related Questions