角度形式控件类型中的枚举?

nat*_*eat 2 forms enums types typescript angular

我在表单类型中使用枚举时遇到问题。

下面的代码:

export enum Frequency {
  DAILY = 'DAILY',
  WEEKLY = 'WEEKLY',
  MONTHLY = 'MONTHLY',
  QUARTERLY = 'QUARTERLY',
  HALF_YEARLY = 'HALF_YEARLY',
  YEARLY = 'YEARLY',
}

export type MyForm = FormGroup <{
  frequency: FormControl<Frequency>,
}>

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  name = 'Angular ' + VERSION.major;

  public form: MyForm = new FormGroup({
    frequency: new FormControl(Frequency.DAILY),
  })

}
Run Code Online (Sandbox Code Playgroud)

给出错误:

Type 'FormGroup<{ frequency: FormControl<Frequency.DAILY>; }>' is not assignable to type 'MyForm'.
Type 'FormControl<Frequency>' is not assignable to type 'FormControl<Frequency.DAILY>'.
Type 'Frequency' is not assignable to type 'Frequency.DAILY'.
Run Code Online (Sandbox Code Playgroud)

stackblitz: https://stackblitz.com/edit/angular-ivy-qsb4nb ?file=src%2Fapp%2Fapp.component.html,src%2Fapp%2Fapp.component.ts

Mol*_*lcs 5

FormGroup通过从类型中删除并将其移动到变量中可以解决该问题form,如下所示:

export type MyForm = {
  frequency: FormControl<Frequency>;
};

public form: FormGroup<MyForm> = new FormGroup<MyForm>({
  frequency: new FormControl(Frequency.DAILY),
});
Run Code Online (Sandbox Code Playgroud)

返回的值new FormGroup不需要输入为 a ,formGroup因为它已经定义为 new FormGroup,您只需要输入它的控件。

这是stackblitz上的一个工作示例。