Advertisement
Guest User

Untitled

a guest
Mar 24th, 2019
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.20 KB | None | 0 0
  1. import { FormGroup, FormControl, ValidatorFn, AsyncValidatorFn, AbstractControlOptions } from '@angular/forms';
  2.  
  3. type TSupported = string | number | boolean;
  4.  
  5. class TypedControl<T extends TSupported> extends FormControl {
  6. constructor(
  7. formState?: any, // TODO any -> T?
  8. validatorOrOpts?: ValidatorFn | ValidatorFn[] | AbstractControlOptions | null | undefined,
  9. asyncValidator?: AsyncValidatorFn | AsyncValidatorFn[] | null | undefined
  10. ) {
  11. super(formState, validatorOrOpts, asyncValidator);
  12. }
  13.  
  14. public static fromFormGroup<G extends TSupported>(fg: FormGroup, controlName: string): TypedControl<G> {
  15. const control = fg.get(controlName);
  16.  
  17. if (control) {
  18. return <TypedControl<G>>control;
  19. } else {
  20. throw new Error('Control not found.');
  21. }
  22. }
  23.  
  24. public getValue(): T {
  25. return <T>this.value;
  26. }
  27.  
  28. public setValue(value: T): void {
  29. super.setValue(value);
  30. }
  31. }
  32.  
  33. const form = new FormGroup({
  34. foo: new FormControl('bar'),
  35. });
  36.  
  37. const fooControl = TypedControl.fromFormGroup<string>(form, 'foo');
  38.  
  39. const value = fooControl.getValue();
  40.  
  41. fooControl.setValue('bar'); // fine
  42. // fooControl.setValue(42); // error
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement