2

I am taking the example of FormControl but it could be applied to any constructor method within a module.

Let's say I would like to add the method myMethod(string): FormControl to the existing FormControl class from ReactiveForm.

I thought I could do it this way:

import {FormControl} from '@angular/forms';

declare module '@angular/forms' {
  interface FormControl {
    myMethod(value: string): FormControl;
  }
}

FormControl.prototype.myMethod = function(value) { /*TODO*/ };

const formControl = new FormControl('').myMethod('hello');

I would have worked with pure javacript, but I have several warnings and errors during typescript compilation:

  • ShadowedName: FormControl
  • 'FormControl' only refers to a type but is used as a value here

Actualy, I think I understand both of the messages, but how can I do here? I have read the official type script documentation on it (https://www.typescriptlang.org/docs/handbook/declaration-merging.html) and cannot find a case that matchs mine...

Thanks a lot!

1 Answer 1

4

The FormControl actually comes from another module within angular, that is the one you need to augment. I found that out by using go to definition command in Visual Studio Code. Also I took the liberty of adding a this parameter to your augmentation function:

import {FormControl} from '@angular/forms';
declare module '@angular/forms/src/model' {
  interface FormControl {
    myMethod(value: string): FormControl;
  }
}
FormControl.prototype.myMethod = function(this: FormControl, value: string) { 
  return this;
};
const formControl = new FormControl('').myMethod('hello');
Sign up to request clarification or add additional context in comments.

3 Comments

At first I wasn't really convinced, then I read somewhere that augmentation must be done on sources and not on already existing declarations. So this is definitely the right answer. Thanks
This works well - don't forget to - import './my-extension'; - in your component file
2024, angular 17 answer pelase?

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.