首页 > 解决方案 > 如何处理这个错误?'类型中缺少索引签名......'

问题描述

我正在尝试丰富 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

显然我做错了什么,我会非常感谢这个问题的一点帮助......

标签: angulartypescriptangular-reactive-forms

解决方案


今天我学习了如何在类中实现索引签名。我缺少的是我没有为类中声明的变量定义任何类型。所以,就我而言,解决方案就像这样简单:

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([]);
}

这是我对索引签名的理解。如果有人想添加或更正任何内容,请随时这样做......


推荐阅读