无法将新方法添加到Angular TypeScript类(FormGroup) [英] Cannot add a new method to an Angular TypeScript class (FormGroup)

查看:70
本文介绍了无法将新方法添加到Angular TypeScript类(FormGroup)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试向Angular的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.

我的Angular4应用程序的form-helper.ts文件中包含以下代码.

I have the following code in a form-helper.ts file in my Angular4 app.

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
}

但是编译器会在FormGroup.prototype.setValueAndErrors行上引发错误.

But the compiler throws an error on the FormGroup.prototype.setValueAndErrors line.

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

推荐答案

以下为我编译:

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

键似乎使用的模块名称是指包含FormGroup的实际模块/文件.

The key seems to be using the module name that refers to the actual module/file that contains the FormGroup.

此外,您将需要解决this的用法.

Also, you will need to address your usage of this.

这篇关于无法将新方法添加到Angular TypeScript类(FormGroup)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆