angular - 如何处理这个错误?'类型中缺少索引签名......'
问题描述
我正在尝试丰富 Josh Hicks 的这个非常好的教程
https://medium.com/@joshblf/dynamic-nested-reactive-forms-in-angular-654c1d4a769a
通过添加一些 FormGroups 和 FormArrays,但在 form-model 类中
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
错误消失。但这仅在stackblitz中!
https://stackblitz.com/edit/form-nested-formarray-with-service
显然我做错了什么,我会非常感谢这个问题的一点帮助......
解决方案
今天我学习了如何在类中实现索引签名。我缺少的是我没有为类中声明的变量定义任何类型。所以,就我而言,解决方案就像这样简单:
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([]);
}
这是我对索引签名的理解。如果有人想添加或更正任何内容,请随时这样做......
推荐阅读
- react-native - 开发服务器返回响应错误代码:500 源模块路径不存在
- svg - SVG 蒙版,使用一个形状的坐标来部分标记另一个形状
- php - 我们如何从 laravel 的控制台 kernel.php 调用控制器方法
- serverless-framework - 防止无服务器自动创建 API 端点
- hadoop - 无法使用 tez 执行引擎启动 hive
- android - Android 理解原生代码中的应用程序崩溃。有内存转储吗?
- java - Spring boot 2 和 Angular 6 登录问题
- c# - Thread.CurrentThread.CurrentUICulture 针对 Android 中的相同设置为同一设备返回不同的 CultureInfo
- html - 引导表 - 会计格式的数字
- c# - 从 c# 类属性中的字符串返回字符串 []