We learned about CurrencyPipe in this post:

CurrencyPipe In Angular 9 With Examples

Using those examples in the post you can easily add CurrencyPipe in your template file.

But in this post, I'll show your the steps to do the same using your TypeScript file.

Step 1

Import CurrencyPipe in your app.module file.

Your app.module file's import section might look like this:


import { Component, OnInit } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import {CurrencyPipe} from '@angular/common';
...
...

Step 2

Add CurrencyPipe to the provider’s array in your app.module file. Step 1 is required for Step 2.

So, your provider's array will look like this:


....
....
  providers: [
    SomeService, 
    OtherService, 
    CurrencyPipe],
....
....

enlightened Always make sure that you have the providers for any services you have created, otherwise you'll get NullInjectorError.

Take a look at this post as well:

Solution To "NullInjectorError: No Provider For Module" In Angular 9

Step 3

Import CurrencyPipe in your component file.

Your component file's import section might look like this:


import { Component, OnInit } from '@angular/core';
import {CurrencyPipe} from '@angular/common';
...
...

Step 4

We need to create a private object for CurrencyPipe service as we do for any other service.

Your constructor part might look like this:


...
...
constructor(private currency_pipe_object: CurrencyPipe) { 
... 
}
...
...

Step 5

Now we need to use the transform pipe method to format the currency.

For example, if you're getting the currency from an API,  you'd like to store it in a variable.


...
...
this.USD_currency = this.USD['currency'];
...
...

And then you'll use that variable and format it like this:


...
...
this.USD_currency = this.currency_pipe_object.transform(this.USD_currency, 'USD'); 
...
...

This will add USD CurrencyPipe. You can change any country pipe supported by Angular.

You can use this Wikipedia list to get the country currency code and add into the CurrencyPipe.

ISO 4217 Wikipedia

Source: https://angular.io/api/common/CurrencyPipe

0 Comments

Leave a reply

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