Free Shipping

Secure Payment

easy returns

24/7 support

  • Home
  • Blog
  • Introduction to Pipes in Angular

Introduction to Pipes in Angular

 July 13  | 0 Comments

Pipes in Angular

In this post, we will be discussing the following points about pipes in Angular:

  • What is a Pipe?
  • Why should Pipes be used?
  • Types of Pipes in Angular
  • Description of Inbuilt and Custom Pipes with examples
  • The source code used in the examples have been attached in the link below.

 

  • What are pipes?

In a business application, we often need to have different visual representations of the same set of data. For example, if we have the number 55555 and we want to format it as currency, i.e., if we want something like ₹55555, so this kind of a thing can be achieved using Pipes.
The responsibility of formatting data in AngularJS 1.x was assigned to filter, but now the core team has renamed the filter component into the pipe to avoid the duplication of names which leads to confusion.
Pipes allow us to change the data inside of a template, i.e., filtering, ordering, formatting dates, numbers, currencies, etc. Pipes are accessed in the template code by using the pipe character | (the same syntax as in Angular 1.x), and then the name of the pipe you want to use as shown below:

What are the advantages of using pipe in Angular?

  • We can output only some filtered elements from an array.
  • We can modify or format the value.
  • We can use them as a function.
  • We can do all of the above combined.
  • Types of Pipe in Angular
  • Inbuilt Pipe
  • Custom Pipe

 

  • Inbuilt Pipe

To understand the meaning of an inbuilt pipe, first create a new project by running the command: ng new project_name 
(The project_name is totally up to you.)

  • Now in your component.ts file, inside your project folder, add the new property myvalue and assign the value “hello” inside the class AppComponent as shown below:
export class AppComponent {
  myvalue = 'Hello';
}

Now, in app.component.html, write: <h1> {{myvalue}} </h1>

<h1> Pipes </h1>
<h2>Inbuilt Pipes </h2>
<h1>
{{myvalue }}
</h1>

After running the command, ng serve, the output which we get is attached below:

  • Objective: To transform the value “Hello” to uppercase using the inbuilt

 

  • Using Inbuilt Pipes

Now, in order to transform the value of myvalue, which is Hello in the upper case, use inbuilt pipe uppercase.
For this, just navigate to your app.component.html file and write: <p>
{{myvalue | uppercase}}  </p>

  • Now, run the command, ng serve, after saving your file. You will get the following output:Let’s discuss one more inbuilt pipe-Date.
     

    • Date

    Create another property, mydate, in app.component.ts inside the class AppComponent as shown below:

    export class AppComponent {
      myvalue = 'Hello';
      myDate=new Date(2002,5,24);
      }
    • We will mention this property into the app.component.html file as shown below:
       <p>
      {{myDate}}
    </p>
    • Save the file and run the ng serve command, you will get the following output:
      • Let’s use an inbuilt pipe date by writing in the app.component.html.
      <p>
        {{myDate | date"}}
      </p>

      The Good thing about built-in-pipe is that you can use inbuilt pipe without any import.

      • Parameterized Pipes

      But, if you want some other date format, then you can take the help of an inbuilt pipe with a parameter which is called parameterized pipe. So, here we may pass a parameter to the date pipe by adding the colon after the pipe and then specify all the arguments which you want to specify.
      Example:
      date: ”MM/dd/yy”  as shown below:

      <p>
       {{myDate | date:"MM/dd/yy"}}
      </p>

      Now, save the file and run the command ng serve in your terminal. You will get an output as shown below:

      • Now, let’s create our own (custom ) pipe:

       

      • Custom Pipe

       
      Objective: Double the value entered by the user.
                               Run the command: ng g p double

      In double.pipe.ts, a class is implementing the interface that is PipeTransform as shown below:

      export class DoublePipe implements PipeTransform {
        transform(value: any, args?: any): any {
          return value*2;
        }
      }

      Here, the pipetransform interface is optional because Angular2 will execute the transform function anyway, i.e., whenever it uses this class as a pipe.
      So, when you use this pipe in your template code, Angular will identify that the pipe is applied to the value prior to the pipe symbol and it will execute this transform function in putting the value it finds before the pipe symbol and possible arguments specified separated by colons for the pipe.
      In the double.pipe.ts, we also have a pipe decorator which sets up a name for a pipe. In my case, the name of the pipe is “double” as shown below:

      @Pipe({
        name: 'double'
      })

      Here, we just want to double each value which we pass to the pipe, namely “double.”
      In app.component.html, I want to have an input where the user can put a value, and finally that passed value gets doubled. We will also add one dummy event which tells Angular 2 to update your UI as shown below:

      <input type="text" #input (keyup)="0">

      Save the file and run the command, ng serve. The output is given below:

      • Let’s use our next custom pipe to filter the list.

      Here, our main aim is to filter the list items.

      • So, first create another pipe, namely filter, by running the command: ng g p filter.
      • In the pipe.ts file, define the array named, resultArray, and this will loop through the array item.
      • Check whether the arguments, which are passed by the user, are matching or not with the array item with the help of a regular expression, and if it matches, just push into the resultArray as shown below:
      import { Pipe, PipeTransform } from '@angular/core';
      @Pipe({
        name: 'filter'
      })
      export class FilterPipe implements PipeTransform {
      transform(value: any, args?: any): any {
        
           if(value.length === 0){
            return value;
          }
          let resultArray=[];
          for(let item of value){
            if(item.match('^.*'+args[0]+'.*$')){
              resultArray.push(item);
            }
          }
          return resultArray;
        }
       
      }
      • Create new property values, which is an array of Strings, in the component.ts file and mention this in app.component.html. with the help of ngFor loop as shown below:
      // app.component.ts
      export class AppComponent {
        values=["milk","bread","butter"];
      }
      • Apply the filter pipe in the ngFor loop and set the filter=”b” (<li *ngFor=”let item of values | filter:’b’”>{{item}}</li>)
      • Save the file and run the command: ng serve.
      // app.component.html
      <ul>
      <li *ngFor="let item of values | filter:'b'">{{item}}</li>
        </ul>
      • Save the file and run the command: ng serve.
      • You will see the following output:As a conclusion, let’s review the inbuilt and custom pipes:
        • Inbuilt Pipes can be used like this:

         

           <p>{{ myString | uppercase}}</p>

         

        • Custom Pipes

        You may create your own pipes. This is easily done by adding the @Pipe decorator to a class.

        @Pipe({
        name: ‘myCustomPipe’ // To be used in your template code
        pure: false // Default is ‘true’, use ‘false’ to create an impure pipe
        })
        class MyCustomPipe {  
              // ...            }
        

        Note: By default, all the pipes that you create are pure pipes. This means that Angular 2 won’t re-run them on the value they are applied to upon each change-detection cycle. This behavior makes sense, as it saves performance.
        Keep visiting our website Acadgild for more updates on Angular and other technologies. Click here to learn Front end web development.

>