We have a Formbuilder with multiple fields. Sometimes, requirements want to toggle certain fields. We can turn them off with If statements validators, and use NgIf in the html. Is there an easy way to toggle multiple fields on a 20 field form, and simplify the syntax?
Is it possible with Formbuilders, or do we have to transfer to form array? Syntax below seems repetitive, curious how it can be simplified,
Currently, have around 20 flag fields.
{
this.customerForm = this.formBuilder.group({
'firstName': [null, [Validators.maxLength(50), PhoneNumberValidator]],
'phoneNumber': [null, [Validators.maxLength(50), PhoneNumberValidator]],
'streetName': [null, [Validators.maxLength(50), PhoneNumberValidator]],
'emailAddress': [null, [Validators.maxLength(50), Validators.email]],
'city': [null, [Validators.required, Validators.maxLength(200)]],
'state': [null, [Validators.maxLength(200)]],
'zip':[null,[Validators.maxLength(200)]]
});
}
ngOnInit() {
// this syntax seems repetitive, how to simplify along with NgIf in html?
if (this.firstNameFlag == false) {
this.customerForm.get('firstName').clearValidators();
this.customerForm.get('firstName').updateValueAndValidity();
}
if (this.phoneNumberFlag == false) {
this.customerForm.get('phoneNumber').clearValidators();
this.customerForm.get('phoneNumber').updateValueAndValidity();
}
if (this.streetNameFlag == false) {
this.customerForm.get('streetName').clearValidators();
this.customerForm.get('streetName').updateValueAndValidity();
}
etc