简体   繁体   English

无法将新方法添加到 Angular TypeScript class (FormGroup)

[英]Cannot add a new method to an Angular TypeScript class (FormGroup)

I am trying to add an additional method to Angular's FormGroup class which will set the state of the group + set error state from the server.我正在尝试向 Angular 的 FormGroup class 添加一个附加方法,它将设置组的 state + 来自服务器的设置错误 state。

I have the following code in a form-helper.ts file in my Angular4 app.我的 Angular4 应用程序的form-helper.ts文件中有以下代码。

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
}

But the compiler throws an error on the FormGroup.prototype.setValueAndErrors line.但是编译器在FormGroup.prototype.setValueAndErrors行上抛出一个错误。

ERROR in C:/dev/AppName/AppName-Client/src/app/shared/utils/form-helper.ts (3,21): Property 'setValueAndErrors' does not exist on type 'FormGroup'. C 中的错误:/dev/AppName/AppName-Client/src/app/shared/utils/form-helper.ts (3,21):类型“FormGroup”上不存在属性“setValueAndErrors”。

The following compiles for me: 以下编译对我来说:

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);
}

The key seems to be using the module name that refers to the actual module/file that contains the FormGroup . 密钥似乎是使用模块名称引用包含FormGroup的实际模块/文件。

Also, you will need to address your usage of this . 此外,您还需要解决this

This worked for the newer version of angular (I am using 13)这适用于较新版本的 angular(我使用的是 13)

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

FormGroup.prototype.setValueAndErrors = function(this: FormGroup, state: any, memberErrors: any): void {
  this.setValue(state);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM