Search code examples
androidangularcomponentsangular17formgroups

Angular how to add Enum to a FormGroup as FormControl?


help is appreciated and thanks in advance for all solutions. I created a FormGroup and want via loop adding FormControls to a FormGroup. This tutorial is from Matt Thornton building a real site with Angular. How is that done in Angular 17 with dynamical created FormControls? I left error message below.

Overload 1 of 2, '(this: FormGroup<{ [key: string]: AbstractControl<any, any>; }>, name: string, control: AbstractControl<any, any>, options?: { emitEvent?: boolean | undefined; } | undefined): void', gave the following error.
    The 'this' context of type 'FormGroup<{ roomName: FormControl<string | null>; location: FormControl<string | null>; }>' is not assignable to method's 'this' of type 'FormGroup<{ [key: string]: AbstractControl<any, any>; }>'.
      Type '{ [key: string]: AbstractControl<any, any>; }' is missing the following properties from type '{ roomName: FormControl<string | null>; location: FormControl<string | null>; }': roomName, location
  Overload 2 of 2, '(name: "roomName" | "location", control: FormControl<string | null>, options?: { emitEvent?: boolean | undefined; } | undefined): void', gave the following error.
    Argument of type '`layout${string}`' is not assignable to parameter of type '"roomName" | "location"'. [plugin angular-compiler]

    src/app/admin/rooms/room-edit/room-edit.component.ts:37:20:
      37 │       this.roomForm.addControl(`layout${layout}`, new FormControl(

room.ts:

export enum Layout {
    THEATER = 'Theater',
    USHAPE = 'U-Shape',
    BOARD = 'Board Meeting'
}

room-edit.component.ts:

import { Component, Input, OnInit } from '@angular/core';
import { Layout, LayoutCapacity, Room } from '../../../model/room';
import { FormControl, FormGroup, Validators } from '@angular/forms';

@Component({
  selector: 'app-room-edit',
  templateUrl: './room-edit.component.html',
  styleUrl: './room-edit.component.css'
})
export class RoomEditComponent implements OnInit{

  @Input()
  room: Room;

  layouts = Object.keys(Layout);
  layoutEnum = Layout;
  layoutTypes: Array<string> = Object.keys(Layout).filter(key => isNaN(+key));

  roomForm = new FormGroup(
    {
      roomName : new FormControl('roomName'),
      location: new FormControl('location'),
    }
  );
  
  constructor() {
    this.room = new Room();
  }

  ngOnInit(): void {
    this.roomForm.patchValue({
      roomName:  this.room.name,
      location: this.room.location
    });

    for (const layout of this.layouts) {
      this.roomForm.addControl(`layout${layout}`, new FormControl(`layout${layout}`));
    }
  }

  onSubmit() {
    this.room.name = this.roomForm.controls['roomName'].value ?? '';
    this.room.location = this.roomForm.value['location'] ?? '';
    this.room.capacities = new Array<LayoutCapacity>();
    console.log(this.room);
  }

  getLayoutByKey(layoutKey: string): Layout {
    return this.layoutEnum[layoutKey as keyof typeof Layout];
  }

}

Solution

  • Just indicate your formGroup is a FormGroup of FormsControls, see the <{[key: string]:FormControl|FormArray}>

     roomForm = new FormGroup<{[key: string]:FormControl|FormArray}>(
        {
          roomName : new FormControl('roomName'),
          location: new FormControl('location'),
        }
      );