Angular2 Using Pipes in Component.js

谁说我不能喝 提交于 2021-01-26 06:10:46

问题


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


回答1:


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);



回答2:


This actually works in an @Injectable display utility service with even less fuss than the previous answer involving modules. I imported my data model (below) and the pipe, then simply added the function. So, if you can't use the pipe directly in markup, use this trick!

export interface MoneyDTO extends SerializableDTO, JsonModelObjectDTO {
  value?: string;
  currency?: string;
}

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

formatMoney(money: MoneyDTO): string {
  const cp: CurrencyPipe = new CurrencyPipe('en-US');

  return money && money.value ? cp.transform(money.value, money.currency || 'USD', 'symbol') : null;
}


来源:https://stackoverflow.com/questions/41840265/angular2-using-pipes-in-component-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!