Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Typescript, Is it possible to add method to external class prototype?

Lets say, I want to add method to NgForm (class)

NgForm.prototype.markAsDirty = function (): void {
    let f: NgForm = this;
    Util.forEach(f.form.controls, (k, v: AbstractControl) => {
        v.markAsDirty(false);
    });
};

Is this somehow possible in typescript?

I am aware of:

  • TypeScript add static helper to prototype of existing class
  • Extending functionality in TypeScript
  • Extending Object.prototype with TypeScript

but it works only for interfaces, not classes.

like image 265
Krzysztof Bogdan Avatar asked Mar 12 '23 05:03

Krzysztof Bogdan


1 Answers

In Angular and TypeScript you usually use inheritance like

export class MyForm extends NgForm {
  ...
}

and register your custom class to be used throughout your application instead of the original class.

bootstrap(AppComponent, [FORM_PROVIDERS, FORM_DIRECTIVES, provide(NgForm, { useClass: MyForm})]);

I haven't investigated if there any additional things to consider that are special to the NgForm, FORM_PROVIDERS or FORM_DIRECTIVES to make this work properly.

like image 58
Günter Zöchbauer Avatar answered Mar 15 '23 11:03

Günter Zöchbauer