Instead of:
this.form.get('heroName').patchValue('He-Man');
angular-typesafe-reactive-forms-helper allows:
this.form.get(x => x.heroName).patchValue('He-Man');
- Get intellisense
- No more misspelled property names
- Refactoring Reactive Forms is back to a trivial IDE rename task
In order to make this work as closely as possible to the Angular way, an abstract class FormGroupTypeSafe<T>
was derived from Angular’s FormGroup
with the intent not to break existing code.
Intellisense on FormGroupTypeSafe.value:
Intellisense on FormGroupTypeSafe.getSafe and then patching the value:
//interface used with FormGroupTypeSafe<T>
interface IHeroFormModel {
name: string,
secretLairs: Array<Address>,
power: string,
sidekick: string
}
/* TypeSafe Reactive Forms Changes */
//old code
//heroForm: FormGroup;
heroForm: FormGroupTypeSafe<IHeroFormModel>;
constructor(
/* TypeSafe Reactive Forms Changes */
//old code - private fb: FormBuilder,
private fb: FormBuilderTypeSafe,
private heroService: HeroService) {
this.createForm();
this.logNameChange();
}
// old code
// this.heroForm = this.fb.group({
// name: '',
// secretLairs: this.fb.array([]),
// power: '',
// sidekick: ''
// });
this.heroForm = this.fb.group<IHeroFormModel>({
name: new FormControl(''),
secretLairs: new FormControl([]),
power: new FormControl(''),
sidekick: new FormControl('')
});
//***** Nested type sample *****
interface IAddressModel {
suburb: string;
postcode: string;
}
interface ICustomerModel {
name: string;
address: IAddressModel
}
this.form = this.fb.group<ICustomerModel>({
name: new FormControl(null, [Validators.required]),
address: this.formBuilder.group<IAddressModel>({
suburb: new FormControl(''),
postcode: new FormControl('', [Validators.required]),
})
});
@angular/forms
and all its peer dependencies.
For a more in detail description of the benefits of this package, read my blog - Angular typesafe reactive forms.
Contributions welcome. I only added features required by my projects, but I know more could be added.
Use it…don’t use it :)