如何在Angular2项目中将moment.js实现为管道 [英] How to implement moment.js as a pipe in an Angular2 project

查看:66
本文介绍了如何在Angular2项目中将moment.js实现为管道的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在angular2项目中实现moment.js库,以便将UTC时间转换为特定时区Europe/london,并使用moment[moment timezone]

I would like to implement moment.js library inside an angular2 project i order to convert a UTC time to a certain time zone Europe/london and that using moment and [moment timezone] 1

到目前为止,我已经使用以下命令在Angular2项目中安装了moment.js:

So far, I have installed moment.js in my Angular2 project using the following command:

npm安装时刻--save

npm install moment --save

这是我当前的代码:

import { Component, Pipe, PipeTransform } from '@angular/core';
import * as moment from 'moment';

@Pipe({ name: 'moment' })
class MomentPipe{
  transform(date, format) {
    return moment(date).format(format);
  }
}

HTML:

我从后端收到的时间作为对象

I received the time from the backend as an object

//time.bookingTime.iso == 2016-07-20T21:00:00.000Z

 {{time.bookingTime.iso | moment}}

这对我不起作用,我认为我的实现方式有误

It didn't work for me and I think that I have wrong implementation

推荐答案

当需要使用它时,必须在@component中指定它:

When you need to use it, you have to specify it in the @component:

@Component({
    moduleId: module.id,
    templateUrl: './xyz.component.html',
    styleUrls: ['./xyz.component.css'],
    pipes: [MomentPipe],
    directives: [...]
})
public export ...

并以这种方式在html中使用它:

and use it in the html in this way:

{{now | momentPipe:'YYYY-MM-DD'}}

顺便说一句,这是我编写管道的方式:

btw, this is my way to write the pipe:

import {Pipe, PipeTransform} from '@angular/core';
import * as moment from 'moment';

@Pipe({
    name: 'momentPipe'
})
export class MomentPipe implements PipeTransform {
    transform(value: Date|moment.Moment, ...args: any[]): any {
        let [format] = args;
        return moment(value).format(format);
    }
}

这篇关于如何在Angular2项目中将moment.js实现为管道的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆