Krzysztof Bogdan
Krzysztof Bogdan

Reputation: 963

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:

but it works only for interfaces, not classes.

Upvotes: 4

Views: 1105

Answers (1)

Günter Zöchbauer
Günter Zöchbauer

Reputation: 657248

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.

Upvotes: 7

Related Questions