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
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]);
}
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With