我使用
EditAddressFormComponent
创建了自定义 ControlValueAccessor
表单控件。
我有一个使用地址表单控件的父表单
CompanyComponent
。
有没有办法在
CompanyComponent
中指定验证器来覆盖 EditAddressFormComponent
的默认子表单控件,例如对于 street1
设置 Validators.maxLength(50)
?
我在
CompanyComponent
中的表格现在看起来像这样:
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),
})
模板中使用的地址是这样的:
<edit-address-form formControlName="companyAddress"></edit-address-form>
我知道如果您将地址用作子表单中的输入,则可以将其设为表单组,但是当您使用自定义 CVA 时,我不确定这是否可行。
我的解决方案是将
EditAddressFormComponent
CVA 提取到基类中,并根据我需要如何配置表单控件来创建单独的实现。
例如我现在有
export class EditCompanyAddressComponent extends EditAddressComponentBase
在这堂课上我可以随心所欲地设计我的表格组
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),
});
}