1

I'm trying to import the moment.js library in angular2. I found the following solution as:

import {Component} from 'angular2/core';
import * as moment from 'moment';

@Component({
  selector: 'app',
  template: require('./app.component.html')
})
export class AppComponent {
  moment:any = moment;
  constructor() {}
}

However, I do not want to import this to every component I have. Is there a way to inject it globally so I can use it in all my components?

2 Answers 2

5

From what I read here, I can provide the momentjs library when bootstrap the whole application like this:

import * as moment from 'moment';
import {provide} from 'angular2/core';
import {bootstrap} from 'angular2/platform/browser';

bootstrap(App, [
    provide("moment", {useValue:moment})
])

Then I can use it in my own component by using DI, like this:

import {Component, OnInit, Inject} from 'angular2/core';

@Component({
  selector: 'app',
  template: require('./app.component.html')
})
export class AppComponent {
  constructor(@Inject("moment") private moment) {}
}
Sign up to request clarification or add additional context in comments.

Comments

5

Derive your components from a common base type that imports moment.

Parent

import * as moment from 'moment';

export class MomentAwareClass {
  moment:any = moment;
  constructor() {}
}

Child

import {Component} from 'angular2/core';

@Component({
  selector: 'app',
  template: require('./app.component.html')
})
export class AppComponent extends MomentAwareClass  {
  constructor() {}
}

Update

A better way is to use Dependency Injection to write a service with the Injectable() decorator, this is better as composition is preferred over inheritance.

import { Injectable } from '@angular/core';
import * as moment from 'moment';

@Injectable()
export class SomeClass {
    public moment: any = moment;
}

2 Comments

Thanks! This is a nice approach. I'd like to wait to see if there are some other alternatives.
You can't inject something something that isn't marked as @injectable. Its just not possible with a 3rd party library like this, unless you wrap it inside a service angular understands. This is probably a better solution than what I described above, because its more compose-able.

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.