0

I've added moment into my project and I would like to know how can I change the behavior of moment.fn.toJSON globally.

Currently, I'm using the constructor to do so and it works. But I don't want to paste this code in all of my controllers.

So here is an extract :

import * as moment from 'moment';

constructor(fb: FormBuilder) {
    moment.fn.toJSON = function () { return this.format(); }
}

Does anyone has an idea ?

2
  • 1
    add this to your main.ts or polyfills.ts, or create an abstract class that your components inherit from. Commented Apr 3, 2017 at 15:34
  • I've finally done with a service instead. It's still not what I would like to do but it works fine. Your solution seems great, I will have to look at it. Thanks! Commented Apr 19, 2017 at 8:42

1 Answer 1

1

Just extend the class in the 3rd party library and add your custom methods as required.

For example:

//1) Extend the class:

 export class MyFormBuilder extends FormBuilder{

     public myCoolMethod(): string{
        return "Awesome stuff!"
     }
 }

//2) Import your class into the "application module" (for system-wide access)

import { MyFormBuilder }     from './Services/MyFormBuilder';
@NgModule({
    declarations: [AppComponent, AppHeader, AppFooter],
    imports:      [BrowserModule, ReactiveFormsModule],
    providers:    [MyFormBuilder],
    bootstrap:    [AppComponent],
})

`

//3) Import, inject and use your extended class and new methods in your code:

import { MyFormBuilder }     from './Services/MyFormBuilder';
export class AppComponent{
    constructor(private fb: MyFormBuilder){}
    pageTitle : string = this.fb.myCoolMethod();
}
Sign up to request clarification or add additional context in comments.

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.