Angular2在Component.js中使用管道 [英] Angular2 Using Pipes in Component.js

查看:80
本文介绍了Angular2在Component.js中使用管道的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习Angular2,我想格式化一个数字,添加千位逗号分隔符.据我所知,可以使用Pipes完成此操作,但我想以编程方式在js文件中以数字格式设置数字格式,而不是以html格式(类似于var | number).

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

首先,我意识到没有可以使用的NumberPipe独立管道(如果我输入错了,请纠正我),最相似的是@ angular2/common中的CurrencyPipe.所以我有这样的东西:

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?
    }

}

但是它引发了以下错误:未处理的承诺拒绝:CurrencyPipe没有提供者!;区域:角形; ...

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

我做错了什么?

谢谢.

致谢

推荐答案

第一件事:您需要声明管道-将其添加到NgModule declarations 部分:

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

declarations: [CurrencyPipe]

第二件事:管道不是可注入的,因此您不能通过使用Angular依赖注入系统来获取其实例.您需要手动创建此管道的新实例,例如:

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

这篇关于Angular2在Component.js中使用管道的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆