We have the option to create a union type |
where all parameters can be marked as optional using ?:
. This allows for more flexibility in usage. Additionally, I consolidated the types into a single union type named UNION_FORM_GROUP_TYPES
.
I chose to keep the types distinct because if you are certain about a specific type like "teacher," you can explicitly cast it using <TeacherForm>
or as TeacherForm
.
export class FireFighterForm {
interventions?: FormControl<number | null> = new FormControl<number | null>(
null
);
}
export class PolicemanForm {
department?: FormControl<number | null> = new FormControl<number | null>(
null
);
}
export class TeacherForm {
specialization?: FormControl<number | null> = new FormControl<number | null>(
null
);
}
export type UNION_FORM_GROUP_TYPES =
| TeacherForm
| PolicemanForm
| FireFighterForm
| null;
FULL CODE:
import { Component, OnInit } from '@angular/core';
import { ImportsModule } from './imports';
import { FormControl, FormGroup } from '@angular/forms';
import { DropdownChangeEvent } from 'primeng/dropdown';
import { FireFighterForm } from './forms/firefighter.form';
import { PolicemanForm } from './forms/policeman.form';
import { TeacherForm } from './forms/teacher.form';
export type UNION_FORM_GROUP_TYPES =
| TeacherForm
| PolicemanForm
| FireFighterForm
| null;
@Component({
selector: 'dropdown-reactive-forms-demo',
templateUrl: './dropdown-reactive-forms-demo.html',
styles: `.card,form { display: flex; flex-direction: column; gap: 10px;}`,
standalone: true,
imports: [ImportsModule],
})
export class DropdownReactiveFormsDemo {
personTypes: string[] = [
'Teacher',
'Policeman',
'Firefighter',
'Bank',
'Shop',
'Insurance Company',
];
selectedPersonType: string | undefined;
formGroup = new FormGroup({
name: new FormControl(''),
surname: new FormControl(''),
additionalInfo: new FormGroup<UNION_FORM_GROUP_TYPES>({}), // HOW TO TYPE PROPERLY?
// additionalInfo: new FormGroup<TeacherForm | PolicemanForm | FireFighterForm | null>(null) // does not work
});
onPersonTypeChange(event: DropdownChangeEvent) {
if (event.value === 'Teacher') {
this.formGroup.setControl(
'additionalInfo',
new FormGroup<UNION_FORM_GROUP_TYPES>(new TeacherForm())
);
} else if (event.value === 'Policeman') {
this.formGroup.setControl(
'additionalInfo',
new FormGroup<UNION_FORM_GROUP_TYPES>(new PolicemanForm())
);
} else if (event.value === 'Firefighter') {
this.formGroup.setControl(
'additionalInfo',
new FormGroup<UNION_FORM_GROUP_TYPES>(new FireFighterForm())
);
}
}
}