英文:
Angular (15) Unable to extend a typed FormGroup
问题
我在使用类型化的 FormGroup 进行实验。
我创建了以下内容:
export interface CustomFormControls {
name: FormControl<string | null>;
content: FormControl<string | null>;
}
export class CustomForm extends FormGroup<CustomFormControls> {
constructor() {
super({
name: new FormControl('name'),
content: new FormControl('content'),
});
}
}
然后我尝试在一个组件中使用它:
form: CustomForm = new CustomForm();
以及在模板中:
<form class="Form" [formGroup]="form">
然而,我遇到了以下错误:
Type 'CustomForm' is not assignable to type 'FormGroup<any>'.
Types of property 'controls' are incompatible.
Type 'CustomFormControls' is not assignable to type '{ [key: string]: AbstractControl<any, any>; }'.
Index signature for type 'string' is missing in type 'CustomFormControls'.
<form class="Form" [formGroup]="form">
我不确定我在这里做错了什么。
英文:
I am messing around with typed FormGroup.
I created the following:
export interface CustomFormControls {
name: FormControl<string|null>
content: FormControl<string|null>
}
export class CustomForm extends FormGroup<CustomFormControls> {
constructor() {
super({
name: new FormControl('name'),
content: new FormControl('content'),
})
}
}
and then I am trying to use it in a component:
form: CustomForm = new CustomForm()
and in my template:
<form class="Form" [formGroup]="form">
However, I am getting the following error:
Type 'CustomForm' is not assignable to type 'FormGroup<any>'.
Types of property 'controls' are incompatible.
Type 'CustomFormControls' is not assignable to type '{ [key: string]: AbstractControl<any, any>; }'.
Index signature for type 'string' is missing in type 'CustomFormControls'.
<form class="Form" [formGroup]="form">
I am not sure to understand what I did wrong in there.
答案1
得分: 4
export interface CustomFormControls {
name: FormControl<string|null>;
content: FormControl<string|null>;
[key: string]: AbstractControl<any, any>;
}
英文:
Try adding an index signature for a string key
export interface CustomFormControls {
name: FormControl<string|null>
content: FormControl<string|null>
[key: string]: AbstractControl<any, any>;
}
答案2
得分: 0
export interface CustomFormControls {
[key: string]: AbstractControl<string, string>;
name: FormControl<string|null>;
content: FormControl<string|null>;
}
英文:
export interface CustomFormControls {
[key: string]: AbstractControl<string, string>;
name: FormControl<string|null>;
content: FormControl<string|null>;
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论