【问题标题】:How I can create Angular custom Date Pipe如何创建 Angular 自定义日期管道
【发布时间】:2018-10-02 10:15:45
【问题描述】:

我正在研究 angular 5 我想创建一个自定义日期管道,允许我从日期中减去一些天数:

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

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

例如,这会显示如下值:2018-08-29

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

类似:

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

这应该显示如下值:2018-08-01

感谢您的帮助

【问题讨论】:

  • 您是否有理由要使用管道执行此操作?使用日期管道本身但在传递日期之前调整日期不是更容易吗?
  • 是的,我从 Web 服务收到数据,该服务返回我在 primng 数据表上显示的对象列表作为我无法在服务端修改的列表

标签: javascript angular angular5


【解决方案1】:

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

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);
  }
}

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

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

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

【讨论】:

    【解决方案2】:

    您可以像明智地为属性创建类一样,我已将环境类用于日期格式 DATE_FORMAT 并默认分配 dd-MM-yyyy 格式并在日期管道中使用。 通过这种方法,只需更改 DATE_FORMAT 的值,我们就可以轻松更改其他地方的日期格式。

    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】:

      创建自定义管道调用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;
        }
      }
      

      这样称呼

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-01-14
        • 2019-10-12
        • 1970-01-01
        相关资源
        最近更新 更多