Angular - Use pipes in services and components

前端 未结 8 1439
南笙
南笙 2020-11-22 09:42

In AngularJS, I am able to use filters (pipes) inside of services and controllers using syntax similar to this:

$filter(\'date\')(myDate, \'yyyy-MM-dd\');
         


        
8条回答
  •  清酒与你
    2020-11-22 10:25

    Yes, it is possible by using a simple custom pipe. Advantage of using custom pipe is if we need to update the date format in future, we can go and update a single file.

    import { Pipe, PipeTransform } from '@angular/core';
    import { DatePipe } from '@angular/common';
    
    @Pipe({
        name: 'dateFormatPipe',
    })
    export class dateFormatPipe implements PipeTransform {
        transform(value: string) {
           var datePipe = new DatePipe("en-US");
            value = datePipe.transform(value, 'MMM-dd-yyyy');
            return value;
        }
    }
    
    {{currentDate | dateFormatPipe }}
    

    You can always use this pipe anywhere , component, services etc

    For example

    export class AppComponent {
      currentDate : any;
      newDate : any;
      constructor(){
        this.currentDate = new Date().getTime();
        let dateFormatPipeFilter = new dateFormatPipe();
        this.newDate = dateFormatPipeFilter.transform(this.currentDate);
        console.log(this.newDate);
    }
    

    Dont forget to import dependencies.

    import { Component } from '@angular/core';
    import {dateFormatPipe} from './pipes'
    

    Custom Pipe examples and more info

提交回复
热议问题