Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do a conditional FormControl

Tags:

angular

I'm creating a FormGroup that is used by two components, but for of them I need to remove a property that it does not need, my code is similar to:

const myForm = new FormGroup({
  'name': new FormControl('', [CustomValidators.required()]),
  'email': new FormControl('', [CustomValidators.required()])
  ])
})

I need to remove the email for the FormGroup when a variable X is false.

Someone has any idea? Thanks

like image 643
Julito Avellaneda Avatar asked Aug 31 '25 16:08

Julito Avellaneda


2 Answers

To conditionally handle FormControl based on variables, use methods addControl and removeControl as a proper solution

const myForm = new FormGroup({
  'name': new FormControl('', [CustomValidators.required()]),
});

if(x) {
  myForm.addControl('email', new FormControl('', Validators.required);
}

Values and other attributes like disabled can also be used together and also an array of validators can be passed

if(x) {
  myForm.addControl('email', new FormControl({value: '[email protected]', disabled: false}, [Validators.requried, CustomValidators.required]);
}
like image 188
Sudharshan Avatar answered Sep 03 '25 22:09

Sudharshan


Something like:

let x = false;
let formGroup = {
    'name': new FormControl('', [CustomValidators.required()])
}

if (x) {
    formGroup['email'] = new FormControl('', [CustomValidators.required()]);
}

const myForm = new FormGroup(formGroup);
like image 41
tymeJV Avatar answered Sep 03 '25 21:09

tymeJV