Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

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
}

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

ERROR in C:/dev/AppName/AppName-Client/src/app/shared/utils/form-helper.ts (3,21): Property 'setValueAndErrors' does not exist on type 'FormGroup'.

like image 969
Peter Morris Avatar asked Jan 31 '23 02:01

Peter Morris


1 Answers

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.

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

like image 134
cartant Avatar answered Feb 05 '23 15:02

cartant