Assign type to formbuilder (angular v14)

668 Views Asked by At

After an Update to angular version 14, typed reactive forms are required.

In my application I had a formbuilder which defined the form. I created the following interface to be able to assign a type to the form.

export class DialogData {

    constructor(
        public type: string = '',
        public allow: boolean = false,
        public min: number = 5,
        public colorCode: string = '#000000',
        public templateName: string = "",   
    ){}
}

I created an interface to make the form of this interfaces type:

export interface ConfigForm {
  type: FormControl<string>;
  allow: FormControl<boolean>;
  min: FormControl<number>;
  colorCode: FormControl<string>;
  templateName: FormControl<string>;

}

    export class ConfigComponent implements OnInit {
    
      data: DialogData;
      form: FormGroup<ConfigForm>;
      private fb: NonNullableFormBuilder,
@Inject(MAT_DIALOG_DATA) data: DialogData) { 
      this.data = data;
  }
ngOnInit() {
    this.form = this.fb.group<ConfigForm>(
      {
        type: [ this.data.type, [Validators.required] ],         
        allow: [ this.data.allowPdf, [] ],
        min: [ this.data.min, [Validators.min(0)] ],
        colorCode: [ this.data.colorCode, [] ],
        templateName: [ this.data.templateName, [Validators.required] ],
      }
    );

When trying to assign the type to formBuilder I get the following error:

Type '(string | ((control: AbstractControl<any, any>) => ValidationErrors)[])[]' is missing the following properties from type 'FormControl<string>': defaultValue, setValue, patchValue, reset, and 54 more.ts(2740)
        config.component.ts: The expected type comes from property 'type' which is declared here on type 'ConfigForm'

I don't quite understand, what is missing here. Please can someoone help?

1

There are 1 best solutions below

1
Gurupad Shivapuje On

type ModelFormGroup<T> = FormGroup<{
  [K in keyof T]: ɵElement<T[K], null>;
}>;

interface ConfigForm {
  type: string;
  allow: boolean;
  min: number;
  colorCode: string;
  templateName: string;
}

form: ModelFormGroup<ConfigForm>;

this.form = this.fb.group(
      {
        type: [this.data.type, [Validators.required] ],         
        allow: [this.data.allowPdf, [] ],
        min: [this.data.min, [Validators.min(0)] ],
        colorCode: [this.data.colorCode, [] ],
        templateName: [this.data.templateName, [Validators.required] ],
      }
    );