How I can create Angular custom Date Pipe

烂漫一生 提交于 2020-05-31 04:18:33

问题


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>  

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

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 ?

Something like :

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

and this should display value like : 2018-08-01

Thanks for any help


回答1:


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>

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




回答2:


You can create class for property like wise I have use environment class for date format DATE_FORMAT and assign by default dd-MM-yyyy format and use in date pipe. By this approach only change the value of DATE_FORMAT and we can easily change the format of date else where.

import { Pipe, PipeTransform } from '@angular/core';
import { environment } from "../../../../environments/environment";
import { DatePipe } from "@angular/common";

@Pipe({
  name: 'dateFormat'
})


export class DateFormatPipe extends DatePipe implements PipeTransform {

  transform(value: any, args?: any): any {
    if(Object.keys(environment).indexOf("DATE_FORMAT") >= 0){
      return super.transform(value, environment.DATE_FORMAT);
    }

    return super.transform(value, 'dd-MM-yyyy');
}

html

<span>{{ data.date | dateFormat }}</span>



回答3:


Create a custom pipe call mypipe

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

@Pipe({ name: 'mypipe' })
export class Mypipe implements PipeTransform {
  transform(date: Date, day: number): string {
    date.setDate(d.getDate()-day);
    return date;
  }
}

call it like this

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


来源:https://stackoverflow.com/questions/52606333/how-i-can-create-angular-custom-date-pipe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!