javascriptangulartypescriptangular2-pipe

Angular2 Using Pipes in Component.js


I'm learning Angular2 and I want to format a number adding thousand comma separator. As far as I have read this can be done using Pipes, the thing is that I want to format the number programmatically in the js file not in html (doing like var | number).

First of all I've realized there is no NumberPipe standalone pipe that I can work with (correct me if I'm wrong) the most similar one is CurrencyPipe in @angular2/common. So I have something like this:

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

@Component({
  templateUrl: 'test.component.html',
  styleUrls: ['./test.component.scss']
})
export class TestComponent {
    public myNumber = 1000;

    constructor(private currencyPipe: CurrencyPipe) {    
        var formatted = this.currencyPipe().transform(this.myNumber, 'MXN', true); // Is this correct?
    }

}

But it throws me the following error: Unhandled Promise rejection: No provider for CurrencyPipe! ; Zone: angular ;...

What am I doing wrong?

Thanks in advance.

Regards


Solution

  • First thing: you need to declare your pipe - add it to the NgModule declarations section:

    declarations: [CurrencyPipe]
    

    Second thing: pipes are not injectables, so you can't take its instance by using Angular dependency injection system. You need to create new instance of this pipe manually, like:

    var formatted = (new CurrencyPipe()).transform(this.myNumber, 'MXN', true);