BlackHoleGalaxy
BlackHoleGalaxy

Reputation: 9682

Angular model driven validator conditional to a control value

I'm currently defining a model driven form with formBuilder. In this form there is a radio button. And if the value of this radio button is true then I want to display additional inputs which only then are required.

If the radio is false then the additional inputs can be empty and must not block form submit.

Here is the formbuilder part, how can I make my scenario work?

initDynamicForm() {
    let name = '';
    let moreData = false;
    let email = '';

    this.dynamicForm = this.formBuilder.group({
      name: [ name, Validators.required ],
      moreData: moreData,
      email: email // HERE: if moreData is true => must be required
    });
  }

Any idea on how to set this dynamically defined Validators.required on email input depending on moreData value?

Fact to mention: dynamicForm is called several times inside a *ngFor loop. Thus I can't defined component level attributes to be used because each form using dynamicForm "template" must work independently.

Upvotes: 1

Views: 143

Answers (1)

AVJT82
AVJT82

Reputation: 73387

If it's acceptable, perhaps the easiest way is to disable email field when the radio button is false, because this means the email-field will not be included in the form, thus it doesn't affect the validity of the form.

So I'd put a function, that checks the value of the radio button:

this.dynamicForm = this.formBuilder.group({
  name: ['', Validators.required ],
  moreData: [false, this.checkMoreData.bind(this)]
  email: ['', Validators.required] 
});

And then the function:

checkMoreData(control: FormControl) {
  if(control.value == true) {
    this.myForm.get('email').enable()
  }
  // we have to check if myForm is not undefined (since it will be upon initialization)
  // also check if the control is not undefined
  else if (this.myForm && control) {
    this.myForm.get('email').disable()
  }
}

In the end, if you do need to get all fields, disabled or not, you can use getRawValue, which also includes any disabled fields.

Demo

Upvotes: 1

Related Questions