top
upGrad KnowledgeHut SkillFest Sale!

Search

Angular JS Tutorial

Pipes are a type of preprocessors or transformers that transform a given value and display it on the page after transformation. Pipes are often used in the templates to present some data to the user in a certain way.Every application takes some data, processes it and presents it to the user. It can receive data from various sources. These sources can be a simple user input or a network call to an API. The application can retrieve the data and prepares it for presentation to the user. Finally it presents this data to the user. This is where it gets a little tricky.A lot of the time, the information that we retrieve is exact and accurate but is not in the proper format. If we present this information as it is to the user, the user may not be able to understand the information. Keeping this in mind, we need to ensure that we present the data to the user in the simplest of ways. Pipes help us modify the information in the templates just before we are about to present it to the user. Let’s understand this with the help of an example.Users prefer to see a date in a simple format like April 15, 1988 rather than the raw string format Fri Apr 15 1988 00:00:00 GMT-0700 (Pacific Daylight Time). We can use a pipe to transform the latter into the former.A pipe takes in data as input and transforms it to a desired output.Built-in PipesThere are several pipes already built into the Angular framework. Not only that, if none of them fit your requirements, you can always write a custom pipe to help you out. In this section, we are going to look at all the predefined pipes that come bundled with the Angular framework.Angular comes with a stock of pipes such as DatePipe, UpperCasePipe, LowerCasePipe, CurrencyPipe, and PercentPipe. Let’s have a look at each one of them and understand when and how to use these prebuilt pipes in Angular.DatePipeA DatePipe is a pipe that is used for formatting dates in Angular templates. It is the one that you would use to format a JavaScript Date object into the desired format. Let’s create an object of type Date in the TS file and initialize it inside the constructor.Next, we can now use this date object in the HTML template.We are using interpolation to render the date on the page. Here is how the result looks like.Clearly, the output is not suitable to be displayed to a user. We do not need to display all the technical details of the date to the user. Since the user is only concerned with the month, day and year, we should display just those to the user. We can do this with the help of the date pipe.To use a pipe, we simply put the pipe simple, right after the object that we need to apply the pipe on followed by the identifier of the pipe - date.The output for the above is as following.Looks better, right?By default, the date pipe will display the date in the user’s local date format, however, you can customize it however you want. The date pipe also accepts a parameter that we can use to specify how we want to format the date. The parameter is a string as shown below.In the string argument that we are passing to the date pipe, MM stands for a two-digit number representing the month, dd for date and yy for the year. The three values are separated by forward slashes. Here is how the output looks like.Similarly, HH, mm, ss are used to represent hours, minutes and seconds respectively. Feel free to try out other formats as well. The possibilities are endless.UpperCasePipeThe uppercase pipe does what it says, it transforms the text into all uppercase. That is its only job.LowerCasePipeThe lowercase pipe does exactly what it says, it transforms the text to all lowercase.TitleCasePipeThe titlecase pipe is used to capitalize the first character of every word in the string. Here is an example of how it works.As you can see in the above example, all the text was lowercase but the titlecase pipe transformed the first characters of all the words to uppercase.DecimalPipeThe decimal pipe is simply used to format numbers in a specified format. It lets you specify the minimum and maximum number of digits to the left and right of the decimal with the help of a string argument.Decimal representation options are specified by a string in the following format:{minIntegerDigits}.{minFractionDigits}-{maxFractionDigits}minIntegerDigits: The minimum number of integer digits before the decimal point. Default is 1.minFractionDigits: The minimum number of digits after the decimal point. Default is 0.maxFractionDigits: The maximum number of digits after the decimal point. Default is 3.{{ 22/7 }}3.142857142857143{{ 22/7 | number }}3.143{{ 22/7 | number:'4.2-2'}}0,003.14{{ 22/7 | number:'2.2-4'}}03.1429{{ 22/7 | number:'1.2-4'}}3.1429CurrencyPipeThe currency pipe is used to format numbers as currency values. It formats the number nicely and also appends the currency symbol or code as specified. This allows us to display numbers more as amounts which accounts for better user experience.Here is how you can use the currency pipe with a number of examples.{{ 123456 | currency }}$123,456.00{{ 123456 | currency:'INR' }}₹123,456.00{{ 123456 | currency:'INR':'code' }}INR123,456.00{{ 123456 | currency:'USD':'code' }}USD123,456.00{{ 123456 | currency:'USD':'symbol' }}$123,456.00{{ 123456 | currency:'USD':'symbol':'4.2-2' }}$123,456.00All the parameters are optional. If none are provided, the pipe tries to use everything according to the device’s local settings.PercentPipeThe percent pipe transforms a number to a percentage string, formatted according to locale rules that determine group sizing and separator, decimal-point character, and other locale-specific configurations.This works very similar to the number pipe except that the value is multiplied by 100 to calculate the percentage.Here is how you can use the percent pipe in a number of ways.{{ 0.12 | percent }}12%{{ 0.1234 | percent:'1.2-2' }}12.34%{{ 0.123456 | percent:'1.2-2' }}12.35% (Notice the roundoff)SlicePipeThe slice pipe is used in combination with the NgFor structural directives. It is used to slice an array to create a new array. It has a required argument which is a number that specified the starting index within the main array from where it will be sliced to form the new array. Optionally, an end index can also be specified as the second argument.Here is an example. We define an array with a few strings.Next, we use an NgFor to render a list of all the values in the animals array but we also use the slice pipe.Since, we passed the value 2 as the starting index, the array will be sliced and we will only see the elements with the index 2 and higher.Optionally, we can also specify the end index.Keep in mind that the item at the start index is included in the sliced array while the item at the end index is not.AsyncPipeThe 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.It is used with Promises and Observables mostly to unwrap their values right inside the template. Let’s have a look at an example.First, we create a Promise of type string that we will be using in our template. Let’s call it name. Next, we will create a method that will assign some text to the name object after 2 second, asynchronously.The getName() method returns a Promise of type string that we assign directly to the name object. So, for the first two seconds, the name is a Promise with type null, but after that it becomes a Promise of type string and has some text inside of it. To access this string that we have inside the Promise, we can use Async pipe as shown below.Here are the results.For the first 2 seconds, you do not see anything. But after 2 seconds, you see the message. To improve upon UX, you can perform a null check on the unwrapped Promise and display another string (something like “Loading…” or “Please wait…”) while the actual value of the name is being fetched.Now, for the first two seconds, the user does not see a blank page. You get a message informing the user that something is happening in the background and they need to wait. After the Promise resolves, we see the actual message.Those are all the Pipes in Angular. See you in the next module.
logo

Angular JS Tutorial

Pipes in Angular

Pipes are a type of preprocessors or transformers that transform a given value and display it on the page after transformation. Pipes are often used in the templates to present some data to the user in a certain way.

Every application takes some data, processes it and presents it to the user. It can receive data from various sources. These sources can be a simple user input or a network call to an API. The application can retrieve the data and prepares it for presentation to the user. Finally it presents this data to the user. This is where it gets a little tricky.

A lot of the time, the information that we retrieve is exact and accurate but is not in the proper format. If we present this information as it is to the user, the user may not be able to understand the information. Keeping this in mind, we need to ensure that we present the data to the user in the simplest of ways. Pipes help us modify the information in the templates just before we are about to present it to the user. Let’s understand this with the help of an example.

Users prefer to see a date in a simple format like April 15, 1988 rather than the raw string format Fri Apr 15 1988 00:00:00 GMT-0700 (Pacific Daylight Time). We can use a pipe to transform the latter into the former.

A pipe takes in data as input and transforms it to a desired output.

Built-in Pipes

There are several pipes already built into the Angular framework. Not only that, if none of them fit your requirements, you can always write a custom pipe to help you out. In this section, we are going to look at all the predefined pipes that come bundled with the Angular framework.

Angular comes with a stock of pipes such as DatePipe, UpperCasePipe, LowerCasePipe, CurrencyPipe, and PercentPipe. Let’s have a look at each one of them and understand when and how to use these prebuilt pipes in Angular.

DatePipe

A DatePipe is a pipe that is used for formatting dates in Angular templates. It is the one that you would use to format a JavaScript Date object into the desired format. Let’s create an object of type Date in the TS file and initialize it inside the constructor.

DatePipe code

Next, we can now use this date object in the HTML template.

DatePipe code

We are using interpolation to render the date on the page. Here is how the result looks like.

Angular Pipes

Clearly, the output is not suitable to be displayed to a user. We do not need to display all the technical details of the date to the user. Since the user is only concerned with the month, day and year, we should display just those to the user. We can do this with the help of the date pipe.

To use a pipe, we simply put the pipe simple, right after the object that we need to apply the pipe on followed by the identifier of the pipe - date.

DatePipe code

The output for the above is as following.

Looks better, right?

By default, the date pipe will display the date in the user’s local date format, however, you can customize it however you want. The date pipe also accepts a parameter that we can use to specify how we want to format the date. The parameter is a string as shown below.

DatePipe code

In the string argument that we are passing to the date pipe, MM stands for a two-digit number representing the month, dd for date and yy for the year. The three values are separated by forward slashes. Here is how the output looks like.

Similarly, HH, mm, ss are used to represent hours, minutes and seconds respectively. Feel free to try out other formats as well. The possibilities are endless.

UpperCasePipe

The uppercase pipe does what it says, it transforms the text into all uppercase. That is its only job.

UpperCasePipe Code

LowerCasePipe

The lowercase pipe does exactly what it says, it transforms the text to all lowercase.

LowerCasePipe Code

TitleCasePipe

The titlecase pipe is used to capitalize the first character of every word in the string. Here is an example of how it works.

TitleCasePipe Code

As you can see in the above example, all the text was lowercase but the titlecase pipe transformed the first characters of all the words to uppercase.

DecimalPipe

The decimal pipe is simply used to format numbers in a specified format. It lets you specify the minimum and maximum number of digits to the left and right of the decimal with the help of a string argument.

Decimal representation options are specified by a string in the following format:

{minIntegerDigits}.{minFractionDigits}-{maxFractionDigits}
  • minIntegerDigits: The minimum number of integer digits before the decimal point. Default is 1.
  • minFractionDigits: The minimum number of digits after the decimal point. Default is 0.
  • maxFractionDigits: The maximum number of digits after the decimal point. Default is 3.
{{ 22/7 }}3.142857142857143
{{ 22/7 | number }}3.143
{{ 22/7 | number:'4.2-2'}}0,003.14
{{ 22/7 | number:'2.2-4'}}03.1429
{{ 22/7 | number:'1.2-4'}}3.1429

CurrencyPipe

The currency pipe is used to format numbers as currency values. It formats the number nicely and also appends the currency symbol or code as specified. This allows us to display numbers more as amounts which accounts for better user experience.

Here is how you can use the currency pipe with a number of examples.

{{ 123456 | currency }}$123,456.00
{{ 123456 | currency:'INR' }}₹123,456.00
{{ 123456 | currency:'INR':'code' }}INR123,456.00
{{ 123456 | currency:'USD':'code' }}USD123,456.00
{{ 123456 | currency:'USD':'symbol' }}$123,456.00
{{ 123456 | currency:'USD':'symbol':'4.2-2' }}$123,456.00

All the parameters are optional. If none are provided, the pipe tries to use everything according to the device’s local settings.

PercentPipe

The percent pipe transforms a number to a percentage string, formatted according to locale rules that determine group sizing and separator, decimal-point character, and other locale-specific configurations.

This works very similar to the number pipe except that the value is multiplied by 100 to calculate the percentage.

Here is how you can use the percent pipe in a number of ways.

{{ 0.12 | percent }}12%
{{ 0.1234 | percent:'1.2-2' }}12.34%
{{ 0.123456 | percent:'1.2-2' }}12.35% (Notice the roundoff)

SlicePipe

The slice pipe is used in combination with the NgFor structural directives. It is used to slice an array to create a new array. It has a required argument which is a number that specified the starting index within the main array from where it will be sliced to form the new array. Optionally, an end index can also be specified as the second argument.

Here is an example. We define an array with a few strings.

SlicePipe code

Next, we use an NgFor to render a list of all the values in the animals array but we also use the slice pipe.

SlicePipe code

Since, we passed the value 2 as the starting index, the array will be sliced and we will only see the elements with the index 2 and higher.

Angular Pipes

Optionally, we can also specify the end index.

SlicePipe code

Angular Pipes

Keep in mind that the item at the start index is included in the sliced array while the item at the end index is not.

AsyncPipe

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.

It is used with Promises and Observables mostly to unwrap their values right inside the template. Let’s have a look at an example.

First, we create a Promise of type string that we will be using in our template. Let’s call it name. Next, we will create a method that will assign some text to the name object after 2 second, asynchronously.

AsyncPipe Code

The getName() method returns a Promise of type string that we assign directly to the name object. So, for the first two seconds, the name is a Promise with type null, but after that it becomes a Promise of type string and has some text inside of it. To access this string that we have inside the Promise, we can use Async pipe as shown below.

AsyncPipe Code

Here are the results.

For the first 2 seconds, you do not see anything. But after 2 seconds, you see the message. To improve upon UX, you can perform a null check on the unwrapped Promise and display another string (something like “Loading…” or “Please wait…”) while the actual value of the name is being fetched.

AsyncPipe Code

Now, for the first two seconds, the user does not see a blank page. You get a message informing the user that something is happening in the background and they need to wait. After the Promise resolves, we see the actual message.

Those are all the Pipes in Angular. See you in the next module.

Leave a Reply

Your email address will not be published. Required fields are marked *

Comments

somasundarapandian

great learning blog!

michael

great blog!

Suggested Tutorials

Node JS Tutorial

Build various types of web applications,command-line application,etc.
Node JS Tutorial

Build various types of web applications,command-line application,etc....

Read More

JavaScript Tutorial

JavaScript is a dynamic computer programming language for the web. JavaScript was first known as LiveScript. Later on, Netscape changed its name to JavaScript because of its popularity and the excitement generated by it. JavaScript is lightweight and most commonly used as a part of web pages supported by most web browsers like Chrome, Internet Explorer, Opera, Safari, Edge, and Firefox.
JavaScript Tutorial

JavaScript is a dynamic computer programming language for the web. Jav...

Read More