如何创建Angular自定义日期管道 [英] How I can create Angular custom Date Pipe

查看:380
本文介绍了如何创建Angular自定义日期管道的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在处理角度5,我想创建一个服装日期点,允许我从日期中减去几天:

I'm working on angular 5 I want to create a costume date pip that allow me to subtract some days from a date :

这就是我显示日期值的方式:

This how I display my date value :

 <span>{{data.nextCertificateUpdate | date:'yyyy-MM-dd'}}</span>  

例如,此显示的值类似于: 2018-08-29

for example this display a value like : 2018-08-29

我问是否可以创建一个管道,让我从该日期开始减去几天,例如28天?

I ask if it's possible to create a pipe that allow me to substract a number of days for example 28 from this date ?

类似的东西:

<span>{{data.nextCertificateUpdate | mypipe:28 }}</span>  

,其显示的值应为: 2018-08-01

感谢您的帮助

推荐答案

除了上面Sachila给出的漂亮答案之外,您还可以在自定义管道本身中实现全部功能.

Adding to the nice answer given by Sachila above, you can also implement the full functionality in your custom pipe itself.

import { Pipe, PipeTransform } from '@angular/core';
import { DatePipe } from '@angular/common';

@Pipe({ name: 'mypipe' })
export class Mypipe implements PipeTransform {
  // adding a default format in case you don't want to pass the format
  // then 'yyyy-MM-dd' will be used
  transform(date: Date | string, day: number, format: string = 'yyyy-MM-dd'): string {
    date = new Date(date);  // if orginal type was a string
    date.setDate(date.getDate()-day);
    return new DatePipe('en-US').transform(date, format);
  }
}

并使用您的自定义管道,例如:

And use your custom Pipe like:

<span>{{data.nextCertificateUpdate | mypipe: 28: 'yyyy-MM-dd'}}</span>

在此处查看工作示例: https://stackblitz.com/edit/angular-995mgb?file=src%2Fapp%2Fapp.component.html

See a working example here: https://stackblitz.com/edit/angular-995mgb?file=src%2Fapp%2Fapp.component.html

这篇关于如何创建Angular自定义日期管道的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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