Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Last Updated: Mar 27, 2024
Medium

Pipe in Angular

Author Avni Gupta
1 upvote
gp-icon
Basics of javascript
Free guided path
10 chapters
68+ problems
gp-badge
Earn badges and level up

Introduction

AngularJS is a popular TypeScript-based open-source web application framework for building dynamic and interactive web applications. One of Angular's key features is its ability to simplify and streamline development by providing powerful tools and features. 

One such feature is the "pipe" mechanism, which allows developers to transform and format data simply and efficiently.

Pipe in Angular

Let’s have a look at what exactly a pipe is in angular. Then we will look at the types of pipes along with some examples.

There are some prerequisites for understanding the concept of pipes in Angular. This includes having knowledge of AngularJSTypeScriptHTML and CSS.

What are Angular Pipes?

Angular Pipes are a part of the Angular framework. It enables the transformation and formatting of improved display in templates. They handle operations such as sorting, filtering, and formatting. It improves data presentation without altering the original data. 

Pipe in Angular

Pipes are applied and integrated into template expressions. It facilitates real-time data adjustment without necessitating adjustments to the component logic.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Parameters in Pipe

Pipes can accept optional parameters that modify their behavior. These parameters are passed to the pipe using the pipe operator (|) and are separated by a colon (:) from the pipe name.

Syntax

{{ myData | myPipe:param1:param2 }}

Parameters

  • myPipe: pipe name
     
  • myData: the data you want to transform using the myPipe pipe
     
  • param1 and param2: the two parameters that you want to pass to the pipe
     

Note that the parameters are separated by colons.

Types of Pipe in Angular

There are two types of pipes in Angular: built-in pipes and custom pipes.

  • Built-in-Piper
  • Custom Pipes

Built-in Pipes

Built-in pipes are pre-defined pipes that come bundled with Angular. These pipes can be used out of the box and are designed to handle various data types and formats. Some examples of built-in pipes include

Pipe Name Description
DatePipe Used to format dates and times.
CurrencyPipe Used to format currency values.
DecimalPipe Used to format numbers with decimal places.
PercentPipe Used to format numbers as percentages.
UppercasePipe Used to convert text to uppercase.
LowercasePipe Used to convert text to lowercase.

To use a built-in pipe, you need to include it in your component's template using the pipe symbol (|) followed by the name of the pipe and any necessary arguments.

For example, to format a date using the built-in DatePipe, you would use the following syntax:

{{ myDate | date:'medium' }}

Here are some other examples using built-in pipes in angular:

  1. SlicePipe: Used to extract a slice of an array or string.
{{ myString | slice:0:5 }}


This code uses the built-in SlicePipe to extract the first five characters of a string, which is stored in the myString variable. The pipe is applied to the myString variable using the pipe symbol (|), followed by the name of the pipe, "slice," and two arguments: the start index, 0, and the end index, 5. This will display the first five characters of the string.
 

2. JsonPipe: Used to display JSON data.

{{ myObject | json }}


This code uses the built-in JsonPipe to display a JavaScript object stored in the myObject variable as a JSON string. The pipe is applied to the myObject variable using the pipe symbol (|), followed by the pipe's name, "json" which will display the object as a JSON string.


3. AsyncPipe: Used to handle asynchronous data.

{{ myData | async }}


This code uses the built-in AsyncPipe to handle asynchronous data stored in the myData variable. The pipe is applied to the myData variable using the pipe symbol (|), followed by the name of the pipe, "async". This will handle the asynchronous data and display the resolved value when available.

These are just a few more examples of Angular's built-in pipes. Using built-in pipes, you can easily format and transform data in your Angular applications and improve the user experience.

Custom Pipes

Custom Pipes are user-defined pipes you can create to perform specific data transformations. Custom pipes can be created using the @Pipe decorator and used the same way as built-in pipes.

Steps to create a Pipe

  • To create a custom pipe, you must define a class that implements the PipeTransform interface.
  • The PipeTransform interface requires you to implement a single method, transform(), which takes in an input value and any optional arguments and returns a converted output value.

For example, here's how you could create a custom pipe that capitalizes the first letter of a string:

Code in TypeScript

  • Typescript

Typescript

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

@Pipe({
 name: 'capitalize'
})
export class CapitalizePipe implements PipeTransform {
 transform(value: string, args?: any): any {
   if (!value) {
     return value;
   }


   return value.charAt(0).toUpperCase() + value.slice(1);
 }
}


Code in HTML

  • HTML

HTML

<p>{{ 'hello, world!' | capitalizeFirstLetter }}</p>

Output on the browser

Hello, world!

Explanation of the Code

First, we have imported the necessary classes from the Angular core module: the Pipe decorator and the PipeTransform interface. Then we define the custom pipe using the @Pipe decorator. The decorator provides a name for the pipe, "capitalize". 

Next, we define the CapitalizePipe class, which implements the PipeTransform interface. The transform() method takes in an input value (in this case, a string) and any optional arguments (which are not used in this example) and returns a transformed output value (also a string). 

The method checks if the input value is null or undefined and returns it unchanged if it is. Otherwise, it capitalizes the first letter of the string using the toUpperCase() method and the slice() method to append the rest of the string.

Once you've defined your custom pipe, you can use it in your component's template in the same way as a built-in pipe:

<p>{{ 'hello world' | capitalize }}</p>

 

The code above demonstrates how to use the custom pipe in an Angular component's template. The string "hello world" is passed as input to the pipe using the pipe symbol (|) followed by the name of the pipe, "capitalize". The resulting output, "Hello world", is displayed in a paragraph element using Angular's interpolation syntax.

Custom pipes are an essential tool for performing data transformations in Angular applications. They allow you to encapsulate complex transformation logic in a reusable and maintainable way and can be easily shared across multiple components and templates.

Classification of Pipe in Angular

In Angular, pipes can be classified as either pure or impure based on their behavior.

Pure Pipes

Pure pipes are pipes that are stateless and immutable. They don't modify the input data and always return the same output for a given input. Pure pipes are called only when Angular detects changes in the input data and caches them for better performance. Examples of pure pipes include the DatePipe, CurrencyPipe, and PercentPipe.

Impure Pipes

Impure pipes can modify the input data and may return different outputs for the same input. Impure pipes are called on every change detection cycle, regardless of whether the input data has changed. This can be a performance concern if the pipe is doing expensive operations. Examples of impure pipes include the AsyncPipe and the SlicePipe with dynamic arguments.

Chaining Multiple Pipes at the same time

Chaining multiple pipes in Angular is a feature that allows you to apply multiple transformations to data in a single expression. Here's an example of how to chain multiple pipes in Angular:

{{ myDate | date:'medium' | uppercase }}


In this example, we are chaining two pipes: the DatePipe and the UppercasePipe. 

Pass the myDate variable through the DatePipe, which formats the date using the "medium" format. Then pass the resulting output through the UppercasePipe, which converts the text to uppercase. The final output is a formatted date string in all uppercase letters.

When chaining pipes, the output of one pipe is passed as input to the next pipe in the chain. You can chain as many pipes as you need to perform the necessary transformations.

Here's another example that demonstrates how to chain multiple custom pipes:

{{ myText | capitalize | truncate:10 }}

 

In this example, we are chaining two custom pipes: the CapitalizePipe and the TruncatePipe. 

Pass the myText variable through the CapitalizePipe, which capitalizes the first letter of the text. Then, pass the resulting output through the TruncatePipe, which truncates the text to a maximum length of 10 characters. The final output is a capitalized and truncated version of the original text.

To chain custom pipes, you can simply separate them with the pipe symbol (|), as you would with built-in pipes.

Chaining pipe is a useful feature that allows you to concisely and efficiently perform complex data transformations. You can create customized data transformations that meet your needs by combining multiple pipes.

Frequently Asked Questions

What are pipes in Angular?

In Angular, Pipes allow data transformation for improved display in templates. They perform formatting, sorting, and filtering functions without altering the data.

What are the 2 types of pipes in Angular?

The two types of pipes in Angular are built-in pipes and custom pipes. Angular provides built-in pipes, while developers create custom pipes for specific needs.

How can we use a pipe in Angular?

Pipes are added to template expressions using the "|" symbol followed by the pipe name and optional parameters.

What is the use of pipe in Angular API call?

Pipes can be used in Angular API calls to modify the fetched data before displaying it. For example, a "month" pipe can format the month data retrieved from an API in a more user-friendly way.

Conclusion

In conclusion, pipes are a powerful and flexible feature in Angular that allows developers to transform and format data simply and efficiently. Whether you are working with dates, numbers, strings, or other data types, pipes provide a simple and elegant solution for performing data transformations in your Angular applications. 

Mastering pipes can take your Angular development skills to the next level and build more sophisticated and powerful web applications.

Check out the following for a better understanding:

Check out some amazing Guided Paths on topics such as the Basics of angularBasics of reactBasics of nodeFundamentals of react native, etc., along with some Contests and Interview Experiences only on Coding Ninjas Studio

Previous article
AngularJS Expressions
Next article
 AngularJS Modules
Guided path
Free
gridgp-icon
Basics of javascript
10 chapters
68+ Problems
gp-badge
Earn badges and level up
Live masterclass