Angular 4 Pipes

In this chapter, we will discuss what are Pipes in Angular 4. Pipes were earlier called filters in Angular1 and called pipes in Angular 2 and 4.

In this chapter we learn about Angular 4 Pipes Syntax
{{ Welcome to Angular 4 | hello}}
The rules is integers, strings, arrays, and date as input separated with | to be converted in the format as required .

Let us consider a few examples using pipes.

In the app.component.ts file, we have defined the title variable
{{title | uppercase}}
{{title | lowercase}}
For make Angular 4 pipes we must follow-
  • Uppercasepipe
  • Lowercasepipe
  • Jsonpipe
  • Decimalpipe
  • Percentpipe

The following line of code will help us define the required variables in app.component.ts file −
import { Component } from '@angular/core';

   selector: 'app-root',
   templateUrl: './app.component.html',
   styleUrls: ['./app.component.css']

export class AppComponent {
   title = 'Angular 4 Project!';
   todaydate = new Date();
   jsonval = {name:'Sophie', age:'28', address:{a1:'Dallas', a2:'Texas'}};
   days = [ "Monday ", "Tuesday ", "Wednesday ", "Thursday", "Friday ", 
            "Saturday ", "Sunday "];

To create a custom pipe, we have created a new ts file. Here, we want to create the sqrt custom pipe. We have given the same name to the file and it looks as follows −

We will use the pipes in the app.component.html file.
<!--The content below is only a placeholder and can be replaced.-->
<div style = "width:100%;">
   <div style = "width:40%;float:left;border:solid 1px black;">
      <h1>Uppercase Pipe</h1>
     {{title | uppercase}}
<h1>Lowercase Pipe</h1> {{title | lowercase}} <h1>Currency Pipe</h1> {{6589.23 | currency:"USD"}}
{{6589.23 | currency:"USD":true}}</b> //Boolean true is used to get the sign of the currency. <h1>Date pipe</h1> <b>{{todaydate | date:'d/M/y'}}
{{todaydate | date:'shortTime'}} <h1>Decimal Pipe</h1> <b>{{ 258.78787814 | number: '3.4-4' }}</b> // 3 is for main integer, 2-2 are for integers to be displayed. </div> <div style = "width:40%;float:left;border:solid 1px black;"> <h1>Json Pipe</h1> {{ jsonval | json }} <h1>Percent Pipe</h1> {{00.54565 | percent}} <h1>Slice Pipe</h1> {{months | slice:2:6}} // here 2 and 6 refers to the start and the end index </div> </div>

Create a First Custom Pipe

we want to create the sqrt custom pipe app.sqrt.ts
import {Pipe, PipeTransform} from '@angular/core';
@Pipe ({
   name : 'sqrt'
export class SqrtPipe implements PipeTransform {
   transform(val : number) : number {
      return Math.sqrt(val);