我正在尝试丰富Josh Hicks的这个非常不错的教程
https://medium.com/@joshblf/dynamic-nested-reactive-forms-in-angular-654c1d4a769a
通过添加一些FormGroups和FormArrays,但在表单模型类中
export class TeamForm {
group1 = new FormGroup(new MyGroupForm(new MyGroup()));
constructor(team: Team) {
if (team.group1) {
this.group1.setValue(team.group1);
}
}
}
此行
group1 = new FormGroup(new MyGroupForm(new MyGroup()));
返回以下错误
Argument of type 'MyGroupForm' is not assignable to parameter of type '{ [key: string]: AbstractControl; }'.
Index signature is missing in type 'MyGroupForm'.
这是MyGroupForm
类
import { FormControl, Validators } from "@angular/forms";
import { MyGroup } from "./mygroup.model";
export class MyGroupForm {
Input1 = new FormControl();
Input2 = new FormControl();
constructor(groupValue: MyGroup) {
this.Input1.setValue(groupValue.Input1);
this.Input1.setValidators([Validators.required]);
this.Input2.setValue(groupValue.Input2);
}
}
这是MyGroup
类
export class MyGroup {
Input1: string;
Input2: string;
constructor(value?) {
if (value) {
this.Input1 = value.Input1;
this.Input2 = value.Input2;
}
}
}
stackblitz中的相同代码在代码编辑器中返回相同的错误,但是构建良好!
现在,这是奇怪的事情!
如果我替换此文件名中的点(。)
mycontrol-form.model.ts
像这样的逗号(,):mycontrol-form,model.ts
错误消失。但这仅是在堆叠闪电战中!
https://stackblitz.com/edit/form-nested-formarray-with-service
显然我做错了,对于此问题的帮助,我将不胜感激...
答案 0 :(得分:0)
今天,我学习了如何在类中实现索引签名。我所缺少的是,我没有为类中的声明变量定义任何类型。因此,在我的情况下,解决方案就这么简单:
export class MyGroupForm {
Input1: FormControl = new FormControl();
Input2: FormControl = new FormControl();
}
现在,如果要为对象定义通用模型,则创建一个类型接口,并在类中实现它,如下所示:
interface IndexSignature {
[key: string]: FormControl;
}
export class MyGroupForm implements IndexSignature {
[key: string]: FormControl;
Input1 = new FormControl();
Input2 = new FormControl();
}
如果我们的对象具有多种类型,则可以这样声明它们:
interface IndexSignature {
[key: string]: FormControl | FormArray;
}
export class MyGroupForm implements IndexSignature {
[key: string]: FormControl | FormArray;
Input1 = new FormControl();
Array1 = new FormArray([]);
}
,或者在FormControl
和FormArray
均为AbstractControl
类型的特定情况下,我们只定义以下类型:
interface IndexSignature {
[key: string]: AbstractControl;
}
export class MyGroupForm implements IndexSignature {
[key: string]: AbstractControl;
Input1 = new FormControl();
Array1 = new FormArray([]);
}
这是我对索引签名的理解。如果有人想添加或更正任何内容,请随意...