Using moment.js in Angular 2 typescript application

后端 未结 5 2152
名媛妹妹
名媛妹妹 2021-02-20 06:21

I\'m struggling in using moment.js library inside an Angular 2 Typescript app. Even after reading the answer to this question I can\'t get it to work.

This is what I did

5条回答
  •  感动是毒
    2021-02-20 07:09

    As pointed out further down moment ships with its own typings now. And @angular/cli have changed aswell. Updated my answer to reflect this.

    npm i --save moment

    import * as moment from 'moment';
    
    export class SomeClass implements OnInit {
    
      date: moment.Moment;
    
      ngOnInit() {
        this.date = moment();
      }
    
    }
    

    is all that is needed with @angular/cli.

    Below is my old outdated answer.

    With angular-cli: So you get Intellisense in VsCode

    edit --> angular-cli-build.js

    module.exports = function(defaults) {
      return new Angular2App(defaults, {
        vendorNpmFiles: [
          ...
    
          'moment/min/**', // add this line
    
          ...
        ]
      });
    };
    

    edit --> system-config.ts

    const map: any = {
      moment: 'vendor/moment/min/moment.min.js' // add this line
    };
    

    In your component:

    import * as moment from 'moment';
    
    ...
    // example of usage
    dates: moment.Moment[] = [];
    
    ngOnInit() {
      let date = moment();
      date.add(2, 'days');
      this.dates.push(date);
    }
    

提交回复
热议问题