无法向Angular TypeScript类(FormGroup)添加新方法

Pet*_*ris 4 typescript angular

我正在尝试向Angular的FormGroup类添加一个额外的方法,该类将从服务器设置组的状态+设置错误状态.

form-helper.ts在Angular4应用程序的文件中有以下代码.

import { FormGroup } from '@angular/forms';

export interface FormGroup {
  setValueAndErrors(state: any, memberErrors: any);
}

FormGroup.prototype.setValueAndErrors = (state: any, memberErrors: any) => {
  this.setValue(state);
  // do some stuff with the memberErrors parameter
}
Run Code Online (Sandbox Code Playgroud)

但是编译器会FormGroup.prototype.setValueAndErrors在行上抛出错误.

C中的错误:/dev/AppName/AppName-Client/src/app/shared/utils/form-helper.ts(3,21):类型'FormGroup'上不存在属性'setValueAndErrors'.

car*_*ant 7

以下编译对我来说:

declare module "@angular/forms/src/model" {
  interface FormGroup {
    setValueAndErrors(this: FormGroup, state: any, memberErrors: any): void;
  }
}

FormGroup.prototype.setValueAndErrors = function(this: FormGroup, state: any, memberErrors: any): void {
  this.setValue(state);
}
Run Code Online (Sandbox Code Playgroud)

密钥似乎是使用模块名称引用包含的实际模块/文件FormGroup.

此外,您还需要解决您的使用问题this.

  • 你对我来说就像英雄:) (2认同)
  • 不用担心。回答这个问题帮助我解决了困扰我一整天的问题。 (2认同)