Category: 8. Angular Pipes

https://static.vecteezy.com/system/resources/thumbnails/045/933/967/small_2x/pipe-valve-3d-icon-pipeline-3d-icon-png.png

  • Custom Pipes

    Custom Pipes in Angular

    custom pipe is a user-defined pipe that allows developers to perform specific transformations that Angular’s built-in pipes can’t achieve. The built-in pipes provide limited functionalities like formatting dates, numbers and strings. However, you can achieve more than that using custom pipes. For example, sorting and filtering.

    In Angular, pipes are functions that format specified data before displaying it in the View.

    Features and Uses of Angular Custom Pipes

    The Angular Custom Pipes provides the following features −

    • Once you define a custom pipe, you can reuse it wherever needed in the application.
    • Like built-in pipes, custom pipes can also be used directly in the template expressions.
    • The logic for custom pipes is written in a separate TypeScript class and applied within the template. This helps in maintaining the code and improving the performance.
    • There are a number of features that you can add using custom pipes to your Angular application, such as digit count, filtering, sorting, password generation and many more.

    Creating a Custom Pipe in Angular

    Follow the steps given below to create a Custom pipe in Angular −

    • Step 1: Create a TypeScript class and export it. By convention, a pipe class should end with the string “Pipe”.
    • Step 2: Decorate the created TypeScript class with @Pipe Decorator. Inside this decorator, specify a name for the pipe.
    • Step 3: In the end, inherit the PipeTransform interface and implement its transform() method.

    Example

    The following example explains about creating a custom Pipe and using it inside an Angular application.

    Step 1: Open Angular CLI and generate a Pipe using the below command −

    ng g pipe digitcount
    

    After executing the above command, you can see these two files −

    CREATE src/app/digitcount.pipe.spec.ts(211 bytes)CREATE src/app/digitcount.pipe.ts(258 bytes)

    Step 2: Let’s create a logic for counting digits in a number using Pipe. Open digitcount.pipe.ts file and add the below code −

    import{ Pipe, PipeTransform }from'@angular/core'; @Pipe({ 
       name:'digitcount'})exportclassDigitcountPipeimplementsPipeTransform{transform(val : number): number {return val.toString().length;}}

    Step 3: Navigate to app.component.html file and use the newly created pipe inside the template as shown below −

    <div><h3> Using Custom DigitCount Pipe </h3><p>Count :-{{ digits | digitcount }}</p></div><router-outlet />

    Step 4: Now, we have added logic to count number of digits in a given number. It’s time to add the final code in app.component.ts file. Here, we import the DigitcountPipe and define a number.

    import{ Component }from'@angular/core';import{ RouterOutlet }from'@angular/router';import{ DigitcountPipe }from'./digitcount.pipe';
    
    @Component({
      selector:'app-root',
      standalone:true,
      imports:[RouterOutlet, DigitcountPipe],
      templateUrl:'./app.component.html',
      styleUrl:'./app.component.css'})exportclassAppComponent{
      digits : number =100;}

    Step 5: Now, run the application using ng serve command. The code will display the following result on the browser −

    Using Custom DigitCount Pipe
    Count :- 3
    
  • Built-in Pipes

    Angular is a TypeScript (a superset of JavaScript) based framework used for building web applications. It offers various built-in features which include routing, data binding, server-side rendering and data transformation and formatting that help to fulfill project requirements.

    Suppose your project requires some data formatting tasks, such as formatting dates, numbers, and text. For this kind of task, pipes are used in Angular to format specified data before displaying it in View. In this tutorial, we are going to cover how Angular built-in pipes work.

    Built-in Pipes in Angular

    Some of the important Angular built-in pipes are given below −

    Let’s see how they work with examples.

    The LowerCasePipe

    The LowerCasePipe is used to convert all letters of the input string to lowercase. If the input value is null or undefined, this pipe returns null.

    Syntax

    Syntax of the LowerCasePipe is given below −

    {{ inputvalue | lowercase }}

    Example

    In this example, we will see the practical implementation of the LowerCasePipe.

    Step 1: Import the @angular/common package and define a string and an array of strings inside the app.component.ts file.

    import{ Component }from'@angular/core';import{ RouterOutlet }from'@angular/router';import{ LowerCasePipe}from'@angular/common';
    
    @Component({
      selector:'app-root',
      standalone:true,
      imports:[RouterOutlet, LowerCasePipe],
      templateUrl:'./app.component.html',
      styleUrl:'./app.component.css'})exportclassAppComponent{
      TutorialName: string ='Angular'; 
      chapterList: string[]=["Binding","Pipe","Services"];}

    Step 2: Open app.component.html file and apply lowercase pipe to each string as shown below −

    <p>The name ofthis Tutorial is {{TutorialName}}</p><p>The first Topic is {{chapterList[0]| lowercase}}</p><p>The second Topic is {{chapterList[1]| lowercase}}</p><p>The third Topic is {{chapterList[2]| lowercase}}</p><router-outlet />

    Once you save all the code changes, run the application to get the following output −

    The name of this Tutorial is Angular
    The first Topic is binding
    The second Topic is pipe
    The third Topic is services
    

    The UpperCasePipe

    The UpperCasePipe is used to convert all letters of the input string to uppercase. If the input value is null or undefined, this pipe returns null.

    Syntax

    The UpperCasePipe has the following syntax −

    {{ inputvalue | uppercase }}

    Example

    The following example shows how to use the UpperCasePipe.

    Step 1: Add the following code in the app.component.ts file.

    import{ Component }from'@angular/core';import{ RouterOutlet }from'@angular/router';import{ UpperCasePipe}from'@angular/common';
    
    @Component({
      selector:'app-root',
      standalone:true,
      imports:[RouterOutlet, UpperCasePipe],
      templateUrl:'./app.component.html',
      styleUrl:'./app.component.css'})exportclassAppComponent{
      TutorialName: string ='Angular'; 
      chapterList: string[]=["Binding","Pipe","Services"];}

    Step 2: Add the below code in the app.component.html file.

    <div> 
       The name ofthis Tutorial is {{TutorialName}}<br>  
       The first Topic is {{chapterList[0]| uppercase }}<br> 
       The second Topic is {{chapterList[1]| uppercase }}<br> 
       The third Topic is {{chapterList[2]| uppercase }}<br></div>

    Once you save all the code changes and refresh the browser, you will get the following output −

    The name of this Tutorial is Angular
    The first Topic is BINDING
    The second Topic is PIPE
    The third Topic is SERVICES
    

    The SlicePipe

    The SlicePipe is used to slice a piece of data from the input string. It creates a new array or string containing sub-string from the specified string based on the start and end positions.

    Syntax

    The below code block contains the syntax of SlicePipe −

    {{ inputvalue | slice:start:end }}

    Where,

    • start − This is the starting position from where the slicing begins.
    • end − This is the position where the slicing should end.

    Example

    The following example illustrates the use of SlicePipe.

    Step 1: First ensure the following code is present in the app.component.ts file

    import{ Component }from'@angular/core';import{ RouterOutlet }from'@angular/router';import{ SlicePipe}from'@angular/common';
    
    @Component({
      selector:'app-root',
      standalone:true,
      imports:[RouterOutlet, SlicePipe],
      templateUrl:'./app.component.html',
      styleUrl:'./app.component.css'})exportclassAppComponent{
      TutorialName: string ='Angular'; 
      chapterList: string[]=["Binding","Pipe","Services"];}

    Step 2: Change the code of app.component.html file with the code given below −

    <div> 
       The name ofthis Tutorial is {{TutorialName}}<br>  
       The first Topic is {{chapterList[0]| slice:1:2}}<br> 
       The second Topic is {{chapterList[1]| slice:1:3}}<br> 
       The third Topic is {{chapterList[2]| slice:2:3}}<br></div>

    Now, refresh the browser, you will get the below result on screen −

    The name of this Tutorial is Angular
    The first Topic is i
    The second Topic is ip
    The third Topic is r
    

    The DatePipe

    This is used to convert the input string to date format. If the input value is null, the DatePipe returns null as an output.

    Syntax

    Syntax of the DatePipe is as follows −

    {{ inputvalue | date:"dateformat"}}

    Where,

    dateformat is the date format the input string should be converted to.

    Example

    Let’s understand the working of DatePipe using a sample example.

    Step 1: Change the code of the app.component.ts file with the following code −

    import{ Component }from'@angular/core';import{ RouterOutlet }from'@angular/router';import{ DatePipe}from'@angular/common';
    
    @Component({
      selector:'app-root',
      standalone:true,
      imports:[RouterOutlet, DatePipe],
      templateUrl:'./app.component.html',
      styleUrl:'./app.component.css'})exportclassAppComponent{
      presentDate =newDate();}

    Step 2: Navigate to the app.component.html file and embed the DatePipe inside HTML element as shown in the given code block −

    <div> 
       Today's date :-{{presentDate | date:"MM/dd/yy"}}</div>

    Once you save all the code changes, you will get the following output −

    Today's date :- 01/07/25
    

    The CurrencyPipe

    The CurrencyPipe converts the input string to currency format. The given input value will be formatted according to the locale rules and optional parameters, such as code, symbol, symbol-narrow and digitsInfo.

    Syntax

    Syntax of the CurrencyPipe is given below −

    {{ inputvalue | currency :'code':'symbol':'symbol-narrow'}}

    Where,

    code − The ISO 4217 currency code, such as ‘USD’ for US dollars or ‘EUR’ for euros.

    symbol − Displays the currency symbol.

    symbol-narrow − Displays a narrow version of the currency symbol.

    digitsInfo − It specifies the number of decimal places and the minimum and maximum number of integer digits.

    NOTE: All the parameters are optional.

    Example

    In this example, we will see the use of CurrencyPipe.

    Step 1: Declare and initialize a number inside the app.component.ts file.

    import{ Component }from'@angular/core';import{ RouterOutlet }from'@angular/router';import{ CurrencyPipe}from'@angular/common';
    
    @Component({
      selector:'app-root',
      standalone:true,
      imports:[RouterOutlet, CurrencyPipe],
      templateUrl:'./app.component.html',
      styleUrl:'./app.component.css'})exportclassAppComponent{
      newValue: number =54213;}

    Step 2: Next, open the app.component.html file and apply the currency pipe to the defined number.

    <div> 
       The number in currency:{{newValue | currency}}</div>

    All the above changes will generate the following result on browser −

    The number in currency: $54,213.00
    

    The PercentPipe

    The PercentPipe is used to convert the input string to percentage format. Like other built-in pipes mentioned above, it also returns null when an undefined or null value is passed.

    Syntax

    The PercentPipe has the following syntax −

    {{ inputvalue | percent :"digitsInfo"}}

    Where,

    digitsInfo controls the formatting of the percentage value. It determines the number of decimal places and the minimum and maximum number of integer digits.

    Example

    Let’s understand how PercentPipe works with the help of an example.

    Step 1: Define a decimal number inside the app.component.ts file. Also, make sure to import the PercentPipe.

    import{ Component }from'@angular/core';import{ RouterOutlet }from'@angular/router';import{ PercentPipe}from'@angular/common';
    
    @Component({
      selector:'app-root',
      standalone:true,
      imports:[RouterOutlet, PercentPipe],
      templateUrl:'./app.component.html',
      styleUrl:'./app.component.css'})exportclassAppComponent{ 
      newValue: number =0.59;}

    Step 2: Make the following changes in app.component.html file.

    <div>
       The given number in percentage:{{newValue | percent}}</div>

    Once you save all the code changes, you will see the following output on your browser −

    The given number in percentage: 59%
    

    The DecimalPipe

    The DecimalPipe formats a number into a string of decimal point numbers. The given input number will be formatted according to the specified digitsInfo parameter.

    Syntax

    The following code block contains the syntax of DecimalPipe.

    {{ inputvalue | decimal :"digitsInfo"}}

    Where,

    digitsInfo − It determines the number of decimal places and the minimum and maximum number of integer digits.

    Example

    The example given below demonstrates the working of DecimalPipe.

    Step 1: First ensure the following code is present in the app.component.ts file.

    import{ Component }from'@angular/core';import{ RouterOutlet }from'@angular/router';import{ DecimalPipe}from'@angular/common';
    
    @Component({
      selector:'app-root',
      standalone:true,
      imports:[RouterOutlet, DecimalPipe],
      templateUrl:'./app.component.html',
      styleUrl:'./app.component.css'})exportclassAppComponent{
      newValue: number =5902;}

    Step 2: Next, ensure the following code is present in the app.component.html file.

    <div> 
       The given number in decimal:{{newValue | number:'1.2-2'}}</div>

    Save all the mentioned changes to get the output.

    The given number in decimal: 5,902.00
    
  • Pipes

    What are Angular Pipes?

    In Angularpipes are functions that format specified data before displaying it in the View. They help to transform and manage data within interpolation, denoted by {{ | }}. Therefore, pipes are sometimes referred to as filters. It accepts arrays, integers and strings as inputs which are separated by a vertical bar “|” symbol.

    Angular Pipes

    Features and Uses of Angular Pipes

    Some of the features and uses of Angular pipes are listed below −

    • Pipes can apply transformations directly within the HTML element.
    • Once a custom pipe is created, it can be reused throughout the Angular application.
    • Multiple pipes can be chained together. The output of one pipe can be passed as input to another pipe.
    • You can use pipes to format and transform numbers, objects, strings, and dates in a way that is suitable for display in the UI.
    • Pipes are used to filter data which means it can show only certain items from a list based on passed conditions.

    How to Use Angular Pipes?

    To use Angular pipes in your application, embed the pipe directly inside template expression. This is done using Angular’s pipe operator which is denoted by a vertical bar character “|”.

    The pipe operator is a binary operator. On the left of this operator, the input value is passed to the transformation function, and the right side operand is the pipe name.

    All the built-in pipes in Angular are available in the @angular/common package. Hence, make sure to import the required pipe from this package by specifying the pipe name in the following command −

    import{ Pipe-Name }from'@angular/common';

    Syntax

    The syntax to use Angular pipe is as follows −

    <html-tag-name>{{ input-value | pipe-name }}</html-tag-name>

    Where,

    html-tag-name can be replaced by any HTML tag, input-value is the input that will be passed into the pipe on the right side of pipe operator.

    Chaining Angular Pipes

    Chaining multiple pipes together is also possible. The output of one pipe can be passed as input to another pipe. And, the chained pipes run from left to right.

    The syntax to chain Angular pipes is as follows −

    <html-tag-name>{{ input-value | pipe1 | pipe2 }}</html-tag-name>

    Passing Parameters to Angular Pipes

    Some Angular pipes allow to configure the transformation by passing parameters. To specify a parameter, append the pipe name with a colon (:) followed by the parameter value.

    The syntax to add parameters to Angular pipes is shown below −

    <html-tag-name>{{ input-value | pipe : parameter }}</html-tag-name>

    Working Example

    The following example illustrates how to use the DatePipe in your Angular application to format dates.

    Step 1: Create a pipe-app application using the below command:

    ng newpipe-app
    

    Step 2: Add the below content in app.component.html file.

    <div> 
       Today's date :-{{presentDate}}</div>

    Step 3: Import @angular/common package and create an Date object inside app.component.ts file −

    import{ Component }from'@angular/core';import{ RouterOutlet }from'@angular/router';import{ DatePipe}from'@angular/common';
    
    @Component({
      selector:'app-root',
      standalone:true,
      imports:[RouterOutlet, DatePipe],
      templateUrl:'./app.component.html',
      styleUrl:'./app.component.css'})exportclassAppComponent{
      title ='pipe-app';
      presentDate =newDate();}

    Step 4: Start your application using the below command −

    ng serve
    

    It will display the following output on your browser −

    Today's date :- Tue Jan 07 2025 11:52:26 GMT+0530 (India Standard Time)
    

    Step 5: Let’s add date pipe in the HTML file.

    <div> 
       Today's date :-{{presentDate | date }}</div>

    Now, you will see the below output on your screen −

    Today's date :- Jan 7, 2025
    

    Step 6: Pass fullDate parameter to the date pipe as shown below −

    <div> 
       Today's date :- {{presentDate | date: 'fullDate' }}</div>

    Step 7: Now, run your application and you can see the below response −

    Today's date :- Tuesday, January 7, 2025
    

    Angular Built-in Pipes

    Angular supports a number of built-in pipes, which are as follows −

    SNo.Pipes & Description
    1.DatePipeIt is used to format a given date value.
    2.UpperCasePipeIt converts individual letters of the specified texts into uppercase.
    3.LowerCasePipeIt transforms individual letters of the specified texts into lowercase.
    4.CurrencyPipeThis pipe is used to transform a given number into a currency string.
    5.DecimalPipeThis pipe formats a number into a string of decimal point number.
    6.PercentPipeIt formats specified numbers into a percentage string.
    7.TitleCasePipeIt is used to convert the specified text to a title case.
    8.JsonPipeThis built-in pipe is used to transform an object to its corresponding JSON string representation.
    9.KeyValuePipeUse this pipe to create an array of key-value pairs from a given object or map.
    10.SlicePipeIt returns a new sub-string from the specified string.