【问题标题】:moment is giving me error in angular 5 html template时刻在 Angular 5 html 模板中给了我错误
【发布时间】:2018-08-27 10:37:03
【问题描述】:

我在 Angular 5 中使用 moment v2.22.0,这就是我在模块中导入它的方式 -

import * as moment from 'moment';

并在组件中使用它作为 -

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

当我在 html 模板中使用它时 -

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

它给了我一个错误信息-

[Angular] Member 'moment' is not callable

谁能告诉我我做错了什么!!

【问题讨论】:

    标签: angular angular5 angular-moment angular2-moment


    【解决方案1】:

    cli(在控制台中运行)

    // install moment js
    npm install moment --save
    

    组件声明(ts)

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

    模板文件(html)

    // template syntax
    <p>{{moment(date_time_variable).format('ll')}}</p>
    

    【讨论】:

    • 感谢您的回答。直接在 HTML 中而不是 .ts 文件中使用 moment 有什么优点/缺点吗?
    【解决方案2】:

    不要使用any,不用它声明

    import * as moment from 'moment';
    moment = moment;
    

    【讨论】:

    • 感谢您的回答。不使用任何特定原因。
    【解决方案3】:

    尝试将moment 导入为:

    import  moment from 'moment';
    

    HTML:

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

    TS:

    getFormat(activeTeam){
       return moment(activeTeam.createdAt).format('LL')
    }
    

    【讨论】:

    • 感谢您的回答。如果在 ngFor 中使用类似的代码,会不会有任何性能问题。
    【解决方案4】:

    不要将moment的类型声明为any,而是将其声明为moment: () =&gt; any;

    【讨论】:

      【解决方案5】:

      删除* as表单导入

      npm install moment --save 安装moment

      Stackblitz Demo

      import  moment from 'moment';
      
      export class ChatComponent {
        moment: any = moment;
      }
      
      <div>{{moment(activeTeam.createdAt).format('LL')}}</div>
      

      【讨论】:

        猜你喜欢
        • 2020-02-22
        • 1970-01-01
        • 1970-01-01
        • 2022-08-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-02-27
        • 2018-08-17
        相关资源
        最近更新 更多