Pipes allows us to transform our data inside our HTML page.
Pipes allows us to transform our data inside our HTML page.
100000
But what we if want to add commas to separate the digits?
We may create a function and apply it to the number.
function addCommas(string){
However, Angular comes with some built-in pipes that we can use to format our data such as numbers, dates, and currency.
<p>
<p>
export class AppComponent {
We can apply the number pipe and it would add commas to our number.
<p>
https://angular.io/api?type=pipe
If we take a look at the documentation for the number pipe, we can see how it can be used and the parameter it contains.
{{ value_expression | number [ : digitsInfo [ : locale ] ] }}
<p>
If we save the project and go to the browser, we will see a minimum of 3 digits on the left of the decimal and 2 digits on the right because we have 3.2.
100,000.00
Creating your own Pipes
To create a pipe, execute the ng generate pipe command.
ng generate pipe Multiply
@Pipe({
The transform method is where we write our logic to transform the data. It gets call when the pipe is applied to a value.
@Pipe({
The value parameter returns the value that the pipe is applied to. and the other parameters are the optional parameters that we can set to change the outcome of the data.
In the return statement, return the value multiplied by 3.
So, when we apply this pipe to a number, it will return the result of the number multiplied by 3.
Go to the app component HTML page and the apply the pipe to the number.
<p>
300,000.00
Adding Parameters & Arguments to Pipes
Let’s say that we want to insert a number to change the amount to multiply.
{{ myNumber | multiply: 15 | number: '3.2' }}
We need to add a parameter in the transform method of the pipe to accept that number. Remove the default parameter and replace it with a number paramter.
Now, instead of multiplying by 3, we can provide our own multiple. If we do not provide any arguments to our pipe, it will use the default value of 3 to multiply our number.
Recap