English English

Pipes - Process your data that you want to display in an efficient way

If you want to process and display data in a certain way, then you should use pipes instead of using or creating a function in a component.

You can use existing pipes or you can create your own pipe, which we will do in this tutorial.

Existing pipes can be directly used in the HTML of your component.

Example of pipes

UpperCasePipe - Transform text string to all upper case.
Usage:

myString | uppercase

 

DatePipe - Format date in a certain format.
Usage:

myDateObject | date: 'dd/MM/yy hh:mm'


Create your own pipe

A pipe can be created by adding a typescript class that implements the interface "PipeTransform". Your code that processes the data (that you want to display) is written in the method "transform".
You can use this "ng" command to create the pipe through your terminal:

ng g pipe myPipe
Example AgeGroup

This pipe does shows the age group for the certain age of a person. It displays whether the person is an infant, minor, or an adult.

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

@Pipe({name: 'ageGroup'})
export class AgeGroupPipe implements PipeTransform {
    transform(age: number): string {
        if(age < 6) {
            return "infant";
        } else if( age < 18) {
            return 'minor';
        } else {
            return 'adult';
        }
    }
}

 

The name of the pipe is defined in the annotation "@Pipe". You have to write the code for your pipe in the method "transform", which must be implemented.
"age" is the value of the variable that is written before the pipe.
The return value of this method "transform" is the value that will be displayed when you use this pipe.

You can use this method now in your HTML of your component like this:

{{personAge | ageGroup}}

If the variable "personAge" has the value "17", then the string "minor" will be displayed.


More about pipes:
https://angular.io/api/core/PipeTransform
https://angular.io/guide/pipes

Category:
We use cookies on our website. They are essential for the operation of the site
Ok