Angular 如何将 Enum 添加到 FormGroup 作为 FormControl?

问题描述 投票:0回答:1

感谢您的帮助,并提前感谢所有解决方案。我创建了一个 FormGroup 并希望通过循环将 FormControls 添加到 FormGroup 中。本教程来自 Matt Thornton 使用 Angular 构建真实网站。在 Angular 17 中,动态创建的 FormControls 是如何做到这一点的? 我在下面留下了错误消息。

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(

房间.ts:

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

房间编辑.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];
  }

}
android angular components angular17 formgroups
1个回答
0
投票

第 1 步:定义您的枚举

export enum UserRole {
  Admin = 'Admin',
  User = 'User',
  Guest = 'Guest'
}

第 2 步:创建 FormGroup 并将枚举添加为 FormControl

import { FormBuilder, FormGroup } from '@angular/forms';
import { UserRole } from './user-role.enum';

export class MyComponent {
  form: FormGroup;
  roles = UserRole; // reference Enum for easy access in the template
  roleOptions = Object.values(UserRole); // get Enum values for UI options

  constructor(private fb: FormBuilder) {
    this.form = this.fb.group({
      role: [UserRole.User] // set default value
    });
  }
}

第3步:在模板中绑定Enum选项

<form [formGroup]="form">
  <label for="role">User Role:</label>
  <select id="role" formControlName="role">
    <option *ngFor="let role of roleOptions" [value]="role">{{ role }}</option>
  </select>
</form>
© www.soinside.com 2019 - 2024. All rights reserved.