如果您使用的是响应式表单,它可能看起来很诱人,但当您意识到 FormGroup 只是一个 JS 对象时,这会很容易。因此,您可以像使用任何其他 JS 对象一样使用它们。
更简单的方法是在服务中实现一个方法,并利用您的 JS/TS 对象知识:
private commonFields;
private roleBasedFields;
private addressForm;
constructor() {
this.commonFields = {
firstName: '',
lastName: ['', Validators.required],
birthday: [null, Validators.required]
};
this.addressForm = {
street: '',
streetNo: null,
zip: null,
city: '',
// and so on...
};
this.roleBasedFields = {
student: {
homeAddress: addressForm,
// add other fields related to student here
},
faculty: {
workAddress: addressForm,
// add other fields here
},
administration: {
mailingAddress: {
...addressForm,
department: ['', Validators.required]
// if the address object is different for a certain role, you can add them like this
},
// add other fields here
},
};
}
buildForm(role: 'student' | 'faculty' | 'administration'): FormGroup {
return new FormGroup({
...this.commonFields,
...this.roleBasedFields[role]
});
}
在组件中,根据您希望它的实现方式,像这样使用它:
someForm: FormGroup;
formArray: FormArray;
ngOnInit() {
this.someForm = this.thatServiceAbove.buildForm('student');
// if it goes in an array
this.formArray = new FormArray([]);
}
// method to push the FormGroup in a FormArray:
generateForm(role: 'student' | 'faculty' | 'administration') {
this.formArray.push(this.thatServiceAbove.buildForm(role));
}
你明白了:D