moment is giving me error in angular 5 html template
Asked Answered
A

5

5

I am using moment v2.22.0 in angular 5, and this is how I have imported it in module -

import * as moment from 'moment';

and using it in component as -

export class ChatComponent {
  .
  .
  .
  public moment: any = moment;
  .
  .
}

and when I am using it in html template -

<div>{{moment(activeTeam.createdAt).format('LL')}}</div>

it is giving me an error message that -

[Angular] Member 'moment' is not callable

can anyone tell me what I am doing wrong !!

Appomattox answered 27/8, 2018 at 10:37 Comment(0)
D
22

cli (run in console)

// install moment js
npm install moment --save

component declaration (ts)

// import and declare moment
import * as moment from 'moment';
moment: any = moment;

template file (html)

// template syntax
<p>{{moment(date_time_variable).format('ll')}}</p>
Doggett answered 23/9, 2019 at 5:14 Comment(1)
Thanks for the answer. Is there any advantage/ disadvantage of using moment directly in HTML rather than .ts file.Triplett
C
5

Don't use any, declare without it

import * as moment from 'moment';
moment = moment;
Circumfuse answered 23/11, 2019 at 14:42 Comment(1)
Thanks for the answer. Any particular reason for not using any.Triplett
M
4

Try to import moment as :

import  moment from 'moment';

HTML:

<div>{{getFormat(activeTeam)}}</div>

TS:

getFormat(activeTeam){
   return moment(activeTeam.createdAt).format('LL')
}
Mechanize answered 27/8, 2018 at 10:46 Comment(1)
Thanks for the answer. Will there be any performance issue if a similar code is used with ngFor.Triplett
E
0

Instead of declaring moment's type as any, declare it as moment: () => any;

Engel answered 27/8, 2018 at 10:44 Comment(0)
P
0

remove * as form import

For install moment from npm install moment --save

Stackblitz Demo

import  moment from 'moment';

export class ChatComponent {
  moment: any = moment;
}

<div>{{moment(activeTeam.createdAt).format('LL')}}</div>
Panama answered 27/8, 2018 at 10:51 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.