I am looking to establish a more robust type-safe connection between an Angular template and a FormGroup. I have an idea in mind but I'm unsure how to properly implement it in TypeScript.
My goal is to utilize an object to define the keys of the controls
within a FormGroup (which is the initial parameter for the FormControl
constructor), as well as bind the formControlName
within the template, all based on a model class.
The rationale behind this approach is to eliminate the reliance on "magic strings" when using strings for the formControlName
attribute. By doing so, the model class becomes the single source of truth, making it easier to refactor the class and automatically update all other references.
For instance, I envision being able to write something similar to the following:
// model class:
class Partner {
id: string;
name: string;
}
// defining static type SomeType = { id: "id", name: "name" } that extends public properties of Partner
// where the property values must match the property names.
// component:
@Component({
template: `
<form [formGroup]="form" (ngSubmit)="onSubmit()" novalidate>
<!-- avoiding the use of magic strings like formControlName="id" -->
<input type="text" [formControlName]="SomeType.id">
<input type="text" [formControlName]="SomeType.name">
</form>
`})
class CreatePartnerComponent {
form = new FormGroup({
SomeType.id: new FormControl(''),
SomeType.name: new FormControl('')
});
}
Thank you!