Angular 10 Tutorial - Pipes
In this tutorial, we will learn about Pipes in Angular 10. A Pipe is used to transform data and is denoted by the symbol |. It takes integers, strings, arrays, and dates as input, separated by |, and transforms the data in the required format, displaying it in the browser.
Angular 10 provides some built-in pipes, including:
- String Pipe
- Date Pipe
- Currency Pipe
- Json Pipe
- Percent Pipe
- Decimal Pipe
- Slice Pipe
Using Pipes in Angular 10
Before using pipes, let's create some properties. Go to the app.component.ts file and create properties:
fullName = "Mark John";
currentDate = new Date();
fruits= ['Mango', 'Orange', 'Apple', 'Pineapple','Banana'];
user = {"name":"Mark John","age":24, "email":"mjohn@gmail.com","Phone":"1234567890"}
Now, let's see the uses of pipes. First, let's see the String Pipe. Go to the app.component.html file and write:
{{fullName}}
Now, you can see the name. Using the pipe, convert it to uppercase by adding the pipe sign and writing "uppercase".
{{fullName | uppercase}}
Now, you can see the name in uppercase. If we want to print the name in lowercase, just write:
{{fullName | lowercase}}
Now, you can see the name in lowercase.
Date Pipe
Now, let's see the Date Pipe. Just print the date by typing:
{{currentDate}}
Now, you can see the current date. If we want to print the date in a specific format, write:
{{currentDate | date:'d/M/y' }}
Now you can
See here the date is in the d M y format.
If we want to print the time only, then just write:
{{currentDate | date :'shortTime'}}
You can see the time.
Json Pipe
Now, let's see the Json Pipe:
{{user | json}}
Here, you can see the JSON-formatted data.
Currency Pipe
Now, let's see the Currency Pipe. For that, just write any amount:
{{25.12}}
You can see the amount here. If we want to print this amount with a currency symbol, then just add the | sign and in double quotes, the currency name "USD".
{{25.12 | currency:'USD'}}
Now, you can see the $25.12.
Decimal Pipe
Now, let's see the Decimal Pipe. For that, just write a decimal value:
{{45.324234234}}
Now, you can see the decimal. Here, if we want to display only 2 numbers after the point, write:
{{fruits}}
Now, you can see the array. If we want to slice this array, for that, just write:
{{fruits | slice:1:3}}
Now, you can see the sliced array, which is sliced from index 1 to 3.
So, in this way, you can use pipes in Angular 10.