Return to site

ANGULAR INTERVIEW QUESTION: What are pipes?

A pipe is a native Angular element, which takes data in input and transforms it to a specified kind of output.

It is mainly for simple display arrangements.

๐“๐ก๐ž๐ซ๐ž ๐š๐ซ๐ž ๐ญ๐ฐ๐จ ๐ค๐ข๐ง๐๐ฌ ๐จ๐Ÿ ๐ฉ๐ข๐ฉ๐ž๐ฌ:

โ€•๐๐š๐ญ๐ข๐ฏ๐ž ๐ฉ๐ข๐ฉ๐ž๐ฌ which are directly available in your templates:

Your birthday is the {{ birthday | date }}

Here, in the example above, we use the pipes to transform a date in a pretty format, easy to read for the user.

The available pipes in Angular are: DatePipe, UpperCasePipe, LowerCasePipe, CurrencyPipe & PercentPipe.

โ€•๐‚๐ฎ๐ฌ๐ญ๐จ๐ฆ ๐ฉ๐ข๐ฉ๐ž๐ฌ that cover cases not covered by Angular:

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

// {{ pokemon.type | pokemonTypeColor }}
@Pipe({name: 'pokemonTypeColor'})
export class PokemonTypeColorPipe implements PipeTransform {
    transform(type: string): string{
        let color:string;
        switch (type) {
               case 'Feu':
                     color= 'red lighten-1';
                     break;
               case 'Eau':
                     color= 'blue lighten-1';
                     break;
               case 'Plante':
                     color= 'green lighten-1';
                     break;
               default:
                     color= 'grey';
                     break;
        }
        return 'chip ' + color;
    }
}

๐˜๐จ๐ฎ ๐œ๐š๐ง ๐œ๐จ๐ฆ๐›๐ข๐ง๐ž ๐ฉ๐ข๐ฉ๐ž๐ฌ:

ย {{ birthday | date | uppercase }}

๐ˆ๐ง ๐œ๐จ๐ง๐œ๐ฅ๐ฎ๐ฌ๐ข๐จ๐ง, Pipes allows doing low complexity data transformations inside templates.

For more complex transformation, you would rather use services or dedicated components.