[英]How to share form validation between 2 Angular components
I have components with forms for add/edit functionality. 我有带有用于添加/编辑功能的表单的组件。 The form fields for both Add and Edit are identical and thus I would like to reuse my form validation in each.
“添加”和“编辑”的表单字段是相同的,因此我想在每个表单字段中重用我的表单验证。 I have the following validation setup in my Add class I am exporting:
我要导出的“添加”类中具有以下验证设置:
export class AddCarriersComponent implements OnInit {
addCarrierForm: FormGroup;
constructor(private fb: FormBuilder) {
this.createForm();
}
createForm() {
this.addCarrierForm = this.fb.group({
carrierName: ['', Validators.required],
contactNumber: ['', Validators.required],
addressLineOne: ['', Validators.required],
addressLineTwo: [''],
city: ['', Validators.required],
state: ['', Validators.required],
county: ['', Validators.required],
zip: ['', Validators.required],
contactName: ['', Validators.required],
contactEmail: ['', [Validators.required, Validators.email]],
phone: [''],
mobile: ['', Validators.required],
carrierAcceptanceDays: [''],
rateRoundingOptions: ['', Validators.required],
subscriptionPlanName: ['', Validators.required],
subscriptionPlanDuration: ['', Validators.required],
subscriptionPlanEffectiveDate: ['', Validators.required]
})
}
ngOnInit() {
}
}
How can I share these validation requirements with my Edit component? 如何与“编辑”组件共享这些验证要求?
Create a class : 创建一个类:
export class Carrier {
name: string;
// etc.
toFormGroup() {
return {
name: [this.name, Validators.required],
// etc.
}
}
}
Now, you can manage it in your components : 现在,您可以在组件中进行管理:
carrier = new Carrier();
form = this.formBuilder.group(this.carrier.toFormGroup());
This allows you to centralize all of your object logic into a single class. 这使您可以将所有对象逻辑集中到一个类中。 For instance, you could add a
persist()
method that will make an HTTP call to your backend, or things like that. 例如,您可以添加一个
persist()
方法,该方法将对您的后端进行HTTP调用,或类似的事情。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.