Saturday, February 11, 2017

Use Moment.js with angular2 application

Recently i was developing an application in angular2 where i had to use a calendar which shows the results for this month, this week and this weekend. I was finding a solution in pure javascript but it was time consuming. I decided to go on with moment.js , this is how i have embedded moment with angular2 application.

Step 1 : npm install moment --save

Step 2 : In your systemjs.config.js file's map array add:

'moment': 'node_modules/moment'

to packages array add:

'moment': { defaultExtension: 'js' }

Step 3 : In your component.ts use: import * as moment from 'moment/moment';

and that's it. Now you should be able to use moment with your application.

Example:
public setDate(term: string) {
    var status: string;
    status = term;
    switch (status) {
      case "today":
        this.fromDate = moment().toDate();
        break;
      case "tomorrow":
        this.fromDate =  moment(new Date()).add(1,'days').toDate();
        break;
      case "weekend":
        this.fromDate = moment().startOf('week').add('days', 6).toDate();;
        this.toDate = moment().startOf('week').add('days', 7).toDate();
        break;
      case "thisweek":
        this.fromDate = moment().startOf('week').toDate();;
        this.toDate = moment().startOf('week').add('days', 7).toDate();
        break;
      case "nextweek":
        this.fromDate = moment().startOf('week').add('days', 7).toDate();
        this.toDate = moment().startOf('week').add('days', 14).toDate();
        break;
      case "thismonth":
        var date = new Date(), y = date.getFullYear(), m = date.getMonth();
        var firstDay = new Date(y, m, 1);
        var lastDay = new Date(y, m + 1, 0);
        this.fromDate = moment(firstDay).toDate();
        this.toDate = moment(lastDay).toDate();
        break;
    }

1 comment:

Gopi Krishna said...

AngularJS is a toolset for building the framework most suited to your application development. It is fully extensible and works well with other libraries. Every feature can be modified or replaced to suit your unique development workflow and feature needs. Read on to find out how.

AngularJS Training in Chennai