Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import { FormGroup, FormControl, ValidatorFn, AsyncValidatorFn, AbstractControlOptions } from '@angular/forms';
- type TSupported = string | number | boolean;
- class TypedControl<T extends TSupported> extends FormControl {
- constructor(
- formState?: any, // TODO any -> T?
- validatorOrOpts?: ValidatorFn | ValidatorFn[] | AbstractControlOptions | null | undefined,
- asyncValidator?: AsyncValidatorFn | AsyncValidatorFn[] | null | undefined
- ) {
- super(formState, validatorOrOpts, asyncValidator);
- }
- public static fromFormGroup<G extends TSupported>(fg: FormGroup, controlName: string): TypedControl<G> {
- const control = fg.get(controlName);
- if (control) {
- return <TypedControl<G>>control;
- } else {
- throw new Error('Control not found.');
- }
- }
- public getValue(): T {
- return <T>this.value;
- }
- public setValue(value: T): void {
- super.setValue(value);
- }
- }
- const form = new FormGroup({
- foo: new FormControl('bar'),
- });
- const fooControl = TypedControl.fromFormGroup<string>(form, 'foo');
- const value = fooControl.getValue();
- fooControl.setValue('bar'); // fine
- // fooControl.setValue(42); // error
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement