Pipes in Angular

Learn via video courses

Angular's pipes transform how data is displayed, offering flexibility in styling, size, and format. In Angular's framework, pipes segregate code, allowing reusable transformations in component templates. They shine in cases like formatting numbers or dates into locale-specific styles. This article delves into the Angular Pipe API. It explores built-in pipes for number and string values and demonstrates how to utilize them effectively in web frontends, ensuring data sync and dynamic presentation without cumbersome JS functions.

What is a Pipe?

The pipe is used to transform data for display purposes without changing the source value. Also, you can use a pipe to filter data efficiently. There are built-in pipes in Angular like date, number, currency, decimal, etc which cover most of the use cases.

For eg. suppose I want to display a salary in a number format. You can easily do that by using pipe {{ salary | number }} rather than making changes in the salary property of the component. Perfect! We can minimize a lot of effort and add more value to productivity.

pipe-architecture

Syntax

To apply pipe, we must mention | (pipe) inside an expression before pipeName. Like above we have value_expression | pipeName. Followed by single/multiple parameters, that can be passed separated by :(colon).

How to Create Your Pipe?

The custom pipe can be created by using CLI command.

Command :

It generates a folder name with pipes and adds statement.pipe.ts inside that folder.

pipe-folder-structure

It also adds an entry into the AppModule declarations array.

After making changes transform function of the pipe would look like the below.

Pipe name must be cammelCase in case it is bigger, for eg. residentAddress, activeRows, etc.

Pipe :

Usage :

Output :

In the above example, we defined StatementPipe along with @Pipe decorator, to specify it as a Pipe. StatementPipe implements the PipeTransform interface. Hence we had to implement the transform function inside the class with transformation logic.

Let's focus transform function.

  • input parameter refers value just before |(pipe) symbol, here it is 'Apple'.
  • After | is the pipe name i.e. statement.
  • value1 parameter is value after 1st :(colun) i.e. 'vitamins'
  • value2 parameter is value after 2nd : i.e. 'minerals'
  • returns concatenated strings to format statement

Types of Pipe

There are two kinds of pipe

Pure (pure: true) :

  • By default pipes are Pure, unless you mention it pure: false in pipe metadata.
  • All built-in pipes are pure
  • Executes pipe only when the source or parameters are changed.
  • If you keep pure function inside the pipe, it can easily go for memoization for optimization purposes.

Impure (pure: false) :

  • Mention pure: false in pipe metadata.
  • It executes each change detection, irrespective of input changed or not.
  • Impure pipes can have a performance impact, but there are some cases where we had to choose impure pipes.

Built-in Pipes

There are multiple built-in pipes provided by the framework. Most of the generally used cases are handled with this pipe. You can see a complete list of built-in pipes here

DatePipe

You can use the date pipe to format the Date object in various flavors.

Syntax :

Parameters :

ParameterData typeDefault Value
formatstring (Optional)Default is 'mediumDate'
timezonestring (Optional)Default is undefined
localestring (Optional)Default is undefined

Usage :

Output :

UpperCasePipe

You can use an uppercase pipe to convert all letters into uppercase.

Syntax :

Usage :

Output :

LowerCasePipe

You can use a lowercase pipe to convert all letters to lowercase.

Syntax :

Usage :

Output :

CurrencyPipe

You can use the currency pipe to format numbers in various currency formats.

Syntax :

Parameters

ParameterData typeDefault Value
currencyCodestring (Optional)Optional. Default is USD
displaystring (Optional)Optional. Default is 'symbol'
digitsInfostring (Optional)Optional. Default is undefined
localestring (Optional)Optional. Default is undefined

Usage :

Output :

DecimalPipe

You can use the decimal pipe to format any number into different formats.

Syntax :

Parameters :

ParameterData typeDefault Value
digitsInfostring (Optional)Optional. Default is undefined
localestring (Optional)Optional. Default is undefined

Usage :

Output :

PercentPipe

You can use the percent pipe to format any number in a percentage format.

Syntax :

Parameters :

ParameterData typeDefault Value
digitsInfostring (Optional)Optional. Default is undefined
localestring (Optional)Optional. Default is undefined

Usage :

Output :

Pipes and Precedence

The pipe operator has higher precedence than any other operator that exists on expression, we can look at the example

Ternary Operator

Suppose x is a pipe, then the expression isYes ? 'Yes' : 'No' | x is parsed as isYes ? 'Yes' : ('No' | titlecase). And it evaluates the 'No' | titlecase first. Which isn't what we expect as a result.

We have to wrap an expression with the () parenthesis to solve this problem.

Pipe Chaining

You can use multiple pipes together, and they will be applied in a similar order as they have been mentioned in the HTML from left to right.

The above expression will be executed in the below order :

  • 'Angular' | slice:1:3 => 'ng'
  • 'ng' | uppercase => NG

Example of Usage of Pipe

We've already seen built-in pipes provide solutions for most generally used cases. We have to admit that, the angular team had put well-thought efforts behind putting all these built-in pipes.

Majorly pipe can be utilized in a couple of ways

  1. Declaratively :
    • By mentioning pipe on HTML expression
    • We've already seen how to use it in HTML, in previous sections.
  2. Imperatively :
    • Inside the TS file
    • We will explore it in the next section.

Usage of Pipe in Component TS File (with Transform)

You can use pipe inside a component/service file as well. Technically we can call it an imperative usage of pipe.

Suppose you wanted to use a pipe inside a component/service. You can simply inject the component inside the constructor. Call the transform method on that instance to get the desired result.

In the above example, we called injected transform method on injected datePipe instance. But yes you may see an error in the console saying "StaticInjectorError no provider for DatePipe"

Add DatePipe to your providers list in your respective module/component.

Conclusion

  • Pipe is the best way to show the data in a different format without changing the original input value
  • How pipe can be reused ?
  • Pipe precedence and chaining
  • Pipe can also be used for collection filtering
  • Learned about pure and impure pipes.