2

A custom class derived from FormGroup in Angular 14:

export interface MyForm<T> extends FormGroup {
  isSaving: boolean;
  value: Required<T>;
  controls: { [key in keyof Required<T>]: FormControl<T> };
  setValue(
    value: Required<T>,
    options?: {
      onlySelf?: boolean;
      emitEvent?: boolean;
    }
  ): void;
  reset(
    value: T,
    options?: {
      onlySelf?: boolean;
      emitEvent?: boolean;
    }
  ): void;
}

A new property added: isSaving

Method to create that form:

export const createMyForm = <T>({
  fb,
  controls,
  options
}: {
  fb: FormBuilder;

  controls: {
    [key in keyof T]: [
      formState: T[key],
      validatorOrOpts?: ValidatorFn | ValidatorFn[] | FormControlOptions | null,
      asyncValidator?: AsyncValidatorFn | AsyncValidatorFn[] | null
    ];
  };
  options?: AbstractControlOptions | null;
}) => {
  // eslint-disable-next-line prefer-const

  const tt = fb.group(controls, options);
  return tt as MyForm<T>;

};

Usage in component:

this.myForm = createMyForm<User>({
      fb,
      controls: {
        username: ['', Validators.required],
        password: ['', Validators.required]
      },
      options: {
      }
    });

I am getting a build error at

return tt as MyForm;

in export const createMyForm code:

Conversion of type 'FormGroup<{ [K in keyof { [key in keyof T]: [formState: T[key], validatorOrOpts?: ValidatorFn | FormControlOptions | ValidatorFn[] | null | undefined, asyncValidator?: AsyncValidatorFn | AsyncValidatorFn[] | null | undefined]; }]: ɵElement<...>; }>' to type 'MyForm' may be a mistake because neither type sufficiently overlaps with the other. If this was intentional, convert the expression to 'unknown' first. Property 'isSaving' is missing in type 'FormGroup<{ [K in keyof { [key in keyof T]: [formState: T[key], validatorOrOpts?: ValidatorFn | FormControlOptions | ValidatorFn[] | null | undefined, asyncValidator?: AsyncValidatorFn | AsyncValidatorFn[] | null | undefined]; }]: ɵElement<...>; }>' but required in type 'MyForm'.ts

Can you share how to extend FormGroup and add a custom property to it?

1 Answers1

0

isSaving is not a member of FormGroup, marking isSaving as an optional member should resolve the error

export interface MyForm<T> extends FormGroup {
  isSaving?: boolean;
  value: Required<T>;
  controls: { [key in keyof Required<T>]: FormControl<T> };
  setValue(
    value: Required<T>,
    options?: {
      onlySelf?: boolean;
      emitEvent?: boolean;
    }
  ): void;
  reset(
    value: T,
    options?: {
      onlySelf?: boolean;
      emitEvent?: boolean;
    }
  ): void;
}
Mr. Stash
  • 2,940
  • 3
  • 10
  • 24