[英]Angular 14 strictly typed reactive forms - How to type FormGroup model using existing interface
[英]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.