5

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'.

2
  • 1
    Aside from the error you've mentioned, this is not going to be what you expect in that arrow function. Commented Jul 5, 2017 at 13:12
  • I can cross that bridge when I get to it :) For now I just want to know why this isn't compiling Commented Jul 5, 2017 at 13:15

2 Answers 2

9

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.

Sign up to request clarification or add additional context in comments.

4 Comments

You are like a hero to me :)
No worries. Answering this has helped me solve a problem that's been bugging me all day.
Post it as a question + answer on here, to save others the time :)
you are awesome!
0

This worked for the newer version of angular (I am using 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);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.