Saturday, May 20, 2017

Have a pipe in Angular 2 that takes in more than one variable!

This pipe called with {{whatever.BirthDay | simpleDate}} is going to give us something like 08/24/74 but what if we wanted to have something a bit more complicated like {{whatever.BirthDay | simpleDate:false:3}} return 08/24/74!!! instead? We could accomodate such a change like so:

import { Pipe, PipeTransform } from '@angular/core';
import { DatePipe } from '@angular/common';
@Pipe({name: 'simpleDate'})
export class SimpleDatePipe implements PipeTransform {
   transform(value: Date, vague: boolean, emphasis: number=0): string {
      let datePipe = new DatePipe("en-US");
      let revamp = datePipe.transform(value, 'MM/dd/yy');
      while (emphasis > 0) {
         if(vague){
            revamp = revamp + "?";
         } else {
            revamp = revamp + "!";
         }
         emphasis--;
      }
      return revamp;
   }
}

 
 

And yet, {{whatever.BirthDay | simpleDate}} would still give 08/24/74 without the code breaking! Yay! The thing at the left of the pipe becomes the first variable at the method signature and the stuff seperated with colons at the right becomes the later variables, everything but the first item that is which denotes which pipe to use.

No comments:

Post a Comment