Pipes in Angular

What is Angular Pipe?

Pipes are used to transform data, when we only need that data transformed in a template. Basically a pipe is an operator that takes a stream of inputs, transforms it, and returns. The pipes may be chained to perform complex operations, or they can be directed with some input parameters.

Pipes work inside the interpolation expression through the pipe operator ( | ) to the pipe function on the right.

Angular comes with a stock of pipes and they are all available for use in any template.

Some common pipes are included in Angular:

  • Date Pipe
  • Case Pipes
  • Decimal Pipe
  • Percent Pipe
  • Currency Pipe
  • Async Pipe

What is Date Pipe?

This pipe formats date values according to values given. A number of symbols can be used to define a custom format, as well as the predefined keywords. The available keywords are the following: ‘medium’, ‘short’, ‘fullDate’, ‘longDate’, ‘mediumDate’, ‘shortDate’, ‘mediumTime’ and ‘shortTime’.

<!-- someDate = Aug 12, 2018, 8:02:05 PM -->
{{ someDate | date:'medium' }} <!-- outputs "Aug 12, 2018, 8:02:05 PM" -->
{{ someDate | date:'fullDate' }} <!-- outputs "Sunday, August 12, 2018" -->
{{ someDate | date:'yy' }} <!-- outputs "18" -->
{{ someDate | date:'Hm' }} <!-- outputs "202" -->

What are the Case Pipes?

These pipes covert text to either lower case, upper case or title case with the respective pipe.

{{ "Some text" | uppercase }} <!-- outputs "SOME TEXT" -->
{{ "Some text" | lowercase }} <!-- outputs "some text" -->
{{ "Some text" | titlecase }} <!-- outputs Some Text" -->	

What is the Decimal Pipe?

This pipe formats numbers according to values given. The minimum number of integer digits, the minimum number of fraction digits and the maximum number of fraction digits can be used as arguments.

{{ 3.1456 | number:'4.3-5' }} <!-- outputs 0,003.1456 -->

What is the Percent Pipe?

The Percent pipe transforms a number into its percentage value.

{{ 1.3495 | percent:'4.3-5'}} <!-- outputs '0,134.950%'-->	

What is Currency Pipe?

The Currency pipe allows to format numbers in different currencies.

{{ 1 | currency:'AUD' }} <!-- outputs 'AUD$1.00' -->
{{ 1 | currency:'USD':true }} <!-- outputs '$1.00' -->

What is Async Pipe?

The async pipe subscribes to an Observable or Promise and returns the latest value it has emitted. When a new value is emitted, the async pipe marks the component to be checked for changes. When the component gets destroyed, the async pipe unsubscribes automatically to avoid potential memory leaks.