Pipes
Pipe is used to transforms the data into another format. It takes data as an input and transform it into an output. Pipe is also used for re-usability purpose. In simple words we can say pipe is a transformer.
For example : If you want to calculate the age from date of birth . so this logic you can implement through pipes.
There are so many built in pipes provided by angular itself. Also we can create the custom pipes.
In this article we will look into built in pipes.
Built In Pipes:
- CurrencyPipe
- DatePipe
- DecimalPipe
- JsonPipe
- LowerCasePipe
- UpperCasePipe
- PercentPipe
- SlicePipe
- AsyncPipe
Lets have a look into these one by one.
1. CurrencyPipe : This pipe is used to format the currency. We need to pass the abbreviation of currency as a first parameter. For Example: INR , EURO, CAD etc.
If you just want to show the currency symbol instead of abbreviation, then you can pass second parameter as ‘symbol-narrow’.
2. DatePipe : This pipe is used to format the date. The first argument is a format string.
If you want to display the short time, you can use shortTime.
If you want to display the full date, you can use fullDate.
If you want to display the date in any specific format for e.g dd/MM/yyyy then
Note: Here date is an instance of new Date(). Means you have to use below code in ts file.
3. DecimalPipe : This pipe is used to format the decimal numbers. The first argument is a format string of the form “{minIntegerDigits}. {minFractionDigits}-{maxFractionDigits}”.
If minIntegerDigits = 3, minFractionDigits = 1 and maxFractionDigits = 2 then output will be
4. JsonPipe : This pipe is used to transform the JavaScript object into json string.
If our sample json is like below –
Then here is the value of json data when we display it on browser without parsing.
Now lets use the json pipe to parse the date then-
5. LowerCasePipe : This pipe is used to transform the string in lowercase. For example-
6. UpperCasePipe : This pipe is used to transform the string in uppercase. For example-
7. PercentPipe : This pipe is used to format the numbers into percent. You need to use the percent pipe and also you can provide some arguments to format the data. For example-
You can give the specific decimal number format also. For Example –
8. SlicePipe : This pipe is used to returns a slice of an array. It takes first argument as start index and second argument as end index. If we will not provide any index then it assumes the start and end index of an array.
Here start index is 1 and end index is 3 so it returns value from 1 to 3 index i.e 2,3.
If we will provide only start index then –
We can provide the negative index as well –
9. AsyncPipe : This pipe accepts an observable or a promise and renders the output without calling the subscribe or then method.
Will see this pipe in details in later articles. And in next tutorial we will learn about the custom pipe.