Is it possible to specify validators in parent form to override children of custom CVA?

67 Views Asked by At

I created a custom EditAddressFormComponent form control using ControlValueAccessor.

I have a parent form CompanyComponent that uses the address form control.

Is there a way to specify validators in CompanyComponent to override default child form controls of EditAddressFormComponent, e.g. for street1 set Validators.maxLength(50)?

My form in CompanyComponent looks like this right now:

new UntypedFormGroup({
    id: new UntypedFormControl(),
    name: new UntypedFormControl('', Validators.required),
    description: new UntypedFormControl('', Validators.required),
    companyAddress: new UntypedFormControl({
        street1: '',
        street2: '',
        city: '',
        stateOrProvince: '',
        country: undefined,
        postalCode: '',
    }, Validators.required),
})

And the address is used in the template like this:

<edit-address-form formControlName="companyAddress"></edit-address-form>

I know you can make the address a form group if you are using it as an input in the child form, but when you're using a custom CVA I'm not sure if it's possible.

1

There are 1 best solutions below

0
On BEST ANSWER

My solution for this was to extract the EditAddressFormComponent CVA into a base class and to create separate implementations depending on how I need to configure the form controls.

E.g. I now have

export class EditCompanyAddressComponent extends EditAddressComponentBase

and in this class I can design my form group however I want

protected createFormBase(): UntypedFormGroup {
    return new UntypedFormGroup({
        street1: new UntypedFormControl('', [ Validators.required, Validators.maxLength(50) ]),
        street2: new UntypedFormControl(''),
        city: new UntypedFormControl('', Validators.required),
        stateOrProvince: new UntypedFormControl('', Validators.required),
        postalCode: new UntypedFormControl('', Validators.required),
        country: new UntypedFormControl('US', Validators.required),
    });
}