繁体   English   中英

在 Angular 中使用类型化的 Reactive Forms 时如何确定 FormControl 的类型?

[英]How to determine the type of a FormControl when using typed Reactive Forms in Angular?

考虑以下简单类型的表单:

const dateControl = new FormControl<number | null>(null);
const monthControl = new FormControl<MonthOption | null>(null);
const yearControl = new FormControl<number | null>(null);

const form = new FormGroup({
  ['date']: this.dateControl,
  ['month']: this.monthControl,
  ['year']: this.yearControl,
});

this.dateControl的类型是FormControl<number | null> FormControl<number | null> ,如您所料。

如果我想单独检索控件,以便可以使用它的值,因此我需要确定 FormControl 的类型以及控件值的类型,我可能想要使用:

const control = form.get('date');

control的类型是AbstractControl<any, any> | null AbstractControl<any, any> | null ,正如您所料,它通过字符串获取控件。

当使用动态生成的 forms 时,可以使用addControl将控件添加到表单中,它会control: any

问:有什么方法可以确定FormControl的实际类型,而不保留对FormControl的引用,它在FormGroup之外?

编辑:

如果我按如下方式构造表单,则类型正确( AbstractControl<number | null, number | null> | null ):

const form = new FormGroup({
  date: this.dateControl,
  month: this.monthControl,
  year: this.yearControl,
});
    
const control = form.get('date');

我试图重现您的代码,但似乎我可以正确推断出类型。

在虚拟组件 class 内部:

form = new FormGroup<{
    date: FormControl<string|null>,
    dynamic?: FormControl<string|null>, // dynamic is optional
    name: FormControl<string|null>,
  }>({
    date: new FormControl('2022-01-21'),
    name: new FormControl('Francesco')
  });
  
  ngOnInit(): void {

    const val = this.form.get('date');

    this.form.addControl('dynamic', new FormControl(''))
    const dynamic = this.form.get('dynamic');
    
    console.log(val, typeof val?.value);          // Prints FormControl, 'string'
    console.log(dynamic, typeof dynamic?.value);  // Prints FormControl, 'string'

更新如果你想使用addControl方法,那么你应该在 FormGroup 中定义一个可选的 FormControl。 但是,如果您需要动态添加许多字段,这可能并不总是可行。 addControl的文档中:

在强类型组中,控件必须属于组的类型(可能作为可选键)。


作为旁注,除非您想显式显示类型,否则可以省略为 FormControls 定义原始类型( new FormControl<string | null> )。 Typescript 会自动推断类型<string | null> <string | null>使用反应形式 API。 默认情况下,所有类型都可nullable

如果您想要可为空的值,您可以:

使用FormBuilder class 的nonNullable属性:

constructor(private fb: FormBuilder) {}

// Sets all controls to be non-nullable
  const registrationForm = this.fb.nonNullable.group({
    username: '',
    email: ''
  });

  // Sets only the "username" control to be non-nullable
  const registrationForm2 = this.fb.group({
    username: this.fb.nonNullable.control(''),
    email: ''
  });

使用NonNullableFormBuilder class (这将使所有控件非Nullable)

constructor(private nnfb: NonNullableFormBuilder) {}

ngOnInit() {
  const registrationForm = this.nnfb.group({
    username: '',
    email: ''
});
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM