Can't add new method to Angular TypeScript class (FormGroup)
I am trying to add an additional method to the Angular FormGroup class that will set the group state + set the error state from the server.
I have the following code in a file form-helper.ts
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 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'.
source to share
The following compilations worked 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, which refers to the actual module / file containing the FormGroup
.
Also, you need to turn to use this
.
source to share