Angular pipes

kirushanthy jeyarajah
3 min readOct 16, 2020

--

A pipe is display-value transformations that you can declare in your HTML. It takes in data as input and transforms it to a desired output”.

Angular pipes very helpful for us. this have some build-in pipes for use and we can also create the custom pipes.

Build-in Pipes

let see how to use this pipes and how to work this pipe.

1.Date pipe

It formats a date value to a string.

in the ts file we mention the date value like below

const myBirthDay =new Date(‘1996–05–19’);

in the html file we print the date using angular date pipe

<p> my_BithDay : {{ myBirthDay | date :’dd/MM/YYYY’}}</p>

so now we got the output ‘19/05/1996’ like this.

2. slice pipe

It transforms a string into a substring of it or an array into a subset of it.

const name=’kirushanthy’

<p> short_name : {{ name | slice : 0: 3 }}</p>

then it’s output => short_name : kiru

another example ,apply to array

const values=[‘red’ , ’blue’ , ’yellow’ , ’purple’ , ’green’];

this out put colors are => blue & yellow

3.Lowercase & Uppercase

it transform the string to all lower case or all uppercase

const name =’Kirushanthy’;

output => In Lowercase : kirushanthy ,In Uppercase : KIRUSHANTHY

4.currency pipe

<b>result1 : {{6589.23 | currency :"USD"}}</b> <b>result2 : {{6589.23 | currency :"USD" :true}}</b>

output=> result1 :USD6,589.23 , result2 :$6,589.23

if we want to get the sign of the currency then use the true boolean like this.

5.percent pipe

<p> {{ 00.54565 | percent }}</p>

output => 54.565%

6.Decimal Pipe

<p> {{546.4567854 | number :’3.4 – 4’ }}</p>

output => 546.4568

in here 3 is for main integer and 4 – 4 are integers to display.

7.json pipe

student = {name : ‘Jhon’ , age:’25’ , subject : ‘Maths’ };

<p> {{ student | json }}</p>

output => { “name”: “Jhon”, ”age : “25”, “subject ”: “ Maths”}

this pipes are very simple and easy to understand .

Next we will see how to create custom pipe.

Custom Pipe

we want to created new ts file. we plan to create the sqrt custom pipe.we have to create file with same name.

first we need to import { Pipe , PipeTransform } from ‘@angular/core’

this is the app.sqrt.ts file

we created class and class name is SqrtPipe. this class will implement the PipeTransform.

This class will take argument as the number and will return the number after taking root.

next we need to import this file to app.module.ts

import { SqrtPipe } from './app.sqrt';

@NgModule({
declarations: [
SqrtPipe
],
....})

finally we call the sqrt pipe where you want

<p> Sqrt root of 36 is :{{ 36 | sqrt }}</p>

Thanks for read this article ,I hope this is helpful for you.😊😊😊

--

--