angularangular-reactive-formsangular-formbuilder

Angular 14/+ FormBuilder not accepting RawValue of object while creating its FormGroup


I've this custom type FormRawValue that returns the JSON/RawValue of any AbstractControl

import { AbstractControl } from '@angular/forms';
export type FormRawValue<T extends AbstractControl> = T extends AbstractControl<any, infer TRawValue> ? TRawValue : never;

and this simple IPerson interface:

import { FormControl, FormGroup } from '@angular/forms';
import { FormRawValue } from './Forms.type';

export interface IPerson {
  id: FormControl<number>;
  name: FormControl<string>;
}

export type Person = FormRawValue<FormGroup<IPerson>>;

In the component code, I've a function that creates a new FormGroup using the JSON rawValue provided to it like this:

public map(data: Person) { // Person is simply the rawValue of IPerson

    let group = this._formBuilder.group<IPerson>(data as any); // works fine but bad appraoch
    let group1 = this._formBuilder.group<IPerson>(data); // should work because 'data' holds exactly the same thing that formBuilder is expecting.
  }

Please check my comments in above code block to understand the problem.

Please also check the running sample here: Example


Solution

  • Using something like this is the solution:

    let group1 = this._formBuilder.group(data); // works fine
    let group2: FormGroup<IPerson> = this._formBuilder.group(data); // works fine