2016-02-25 67 views
12

我注意到在Angular 2中有一個叫做CurrencyPipe的管道,它將從一個數字中過濾掉一些小數。這也增加了ISO貨幣指標,即「美元」或任何其他本地貨幣。貨幣和號碼之間的角2貨幣空間?

我的問題是,輸出顯示如下:

USD123 

沒有美元和123之間的空間,這是真的首選的行爲?我是否必須爲此編寫自己的管道,或者有什麼可以添加空間的方法嗎?

下面是一些代碼:

<span>{{ product.price | currency:'USD' }}</span> 
+0

你可以請示出一些代碼嗎? –

+0

當然!如何加入 – theva

+0

如何:' {{product.price |貨幣:'USD'}}' – Martin

回答

6

這是不可能的,因爲CurrencyPipe依靠Intl.NumberFormat並沒有爲這個沒有選項。

這就是說,你可以切換與symbolDisplay參數設置爲true顯示$而不是USD

<span>{{ product.price | currency:'USD':true }}</span> 

這將顯示:$123這是一個好一點;-)如果這個不適合你,你需要實現一個自定義的管道來格式化你的電話號碼......

請參見以下鏈接瞭解詳情:

+0

我明白了。有沒有人發現這個管道有用呢?我看不到有人可能想要顯示沒有空間的貨幣......我必須找到另一種解決方案。 – theva

3

您可以解決使用使用first-letter pseudo element有點聰明CSS的這個問題,添加一個類你跨度:

<span class="price">{{ product.price | currency:'USD':true }}</span> 

,並在你的CSS加:

.price { 
    display: inline-block; 
} 

.price::first-letter { 
    padding-right: 0.3em; 
} 

第一條規則確保您的價格在塊容器框( ::first-letter可以在inline顯示塊上工作),第二條規則在貨幣符號後面添加一些額外的填充。

你可以根據自己的喜好調整它...

5

你真的需要使用貨幣管道嗎?您可以隨時從量分開貨幣:

<span class="price">{{ product.currency }} {{ product.price|number:'1.2-2'}}</span>

或在您的情況:

<span class="price">USD {{ product.price|number:'1.2-2'}}</span>

+0

這隻適用於不改變語言的情況。在德國,貨幣在數字之後。 –

+0

適合我! :) –

1

使自己的自定義貨幣管。

import { Pipe, PipeTransform } from '@angular/core'; 
import { CurrencyPipe } from '@angular/common'; 

@Pipe({ name: 'myCurrency' }) 
export class MyCurrencyPipe implements PipeTransform { 
    transform(num: any, currencyCode: string, showSymbol: boolean, digits: string): any { 
     let value = new CurrencyPipe(navigator.language).transform(num, currencyCode, showSymbol, digits); 
     let firstDigit = value.match(/\d/); 
     let symbol = value.slice(0, firstDigit.index); 
     let amount = value.slice(firstDigit.index); 
     return symbol + " " + amount; 
    } 
} 

,並用它在 HTML

{{amount | myCurrency: currencyCode :true:'1.0-2'}} 
0

您可以覆蓋管如下。 確保你在模塊中包括這個

import {Pipe, PipeTransform} from "@angular/core"; 
import {CurrencyPipe} from "@angular/common"; 


@Pipe({name: 'currency'}) 
export class MyCurrencyPipe extends CurrencyPipe implements PipeTransform { 
    transform(value: any, currencyCode: string, symbolDisplay: boolean, digits: string): string { 
    const currencyFormat = super.transform(value, currencyCode, symbolDisplay, digits); 
    const firstDigit = currency_format.search(/\d/); 
    return currency_format.substring(0, firstDigit) + ' ' + currency_format.substr(firstDigit); 
    } 
}