【发布时间】:2016-10-21 21:16:57
【问题描述】:
如果数字是字符串格式并且字符串中没有小数点,则角度货币管道不会将字符串/int转换为货币格式。
假设金额为 12,我想显示 12.00 美元,如果通过了“12”,则不显示,但如果通过了 12.00,则它可以正常工作。
//Code
import {Pipe, PipeTransform} from "@angular/core";
import {CurrencyPipe} from "@angular/common";
const _NUMBER_FORMAT_REGEXP = /^(\d+)?\.((\d+)(-(\d+))?)?$/;
@Pipe({name: 'myCurrency'})
export class MyCurrencyPipe implements PipeTransform {
constructor (private _currencyPipe: CurrencyPipe) {}
transform(value: any, currencyCode: string, symbolDisplay: boolean, digits: string): string {
if (typeof value === 'number' || _NUMBER_FORMAT_REGEXP.test(value)) {
return this._currencyPipe.transform(value, currencyCode, symbolDisplay, digits);
} else {
return value;
}
}
}
@Component({
selector: 'my-app',
template: `
<div>
<h2>Hello {{name}}</h2>
<div>{{priceNoDecimal}}</div> {{priceNoDecimal | myCurrency}}
<div>{{priceWithDecimal}}</div> {{priceWithDecimal | myCurrency}}
</div>
`,
})
export class App {
name:string;
priceWithDecimal: string;
priceNoDecimal: string;
constructor() {
this.name = 'Angular2',
this.priceNoDecimal = "12"
this.priceWithDecimal = "12.00"
}
}
@NgModule({
imports: [ BrowserModule ],
declarations: [ App , MyCurrencyPipe],
providers: [CurrencyPipe],
bootstrap: [ App ]
})
export class AppModule {}
//output
Hello Angular2
12
12
12.00
USD12.00
【问题讨论】:
-
什么意思?
"12"和"12.00"都转换为USD12.00。 -
您链接到的示例 plunker 运行良好,在第一行中您没有在 div 内应用管道变换。
-
@StefanSvrkota 是的。这就是我想要的,但它没有发生
-
@silentsod,我现在编辑了 plunker。请查看plnkr.co/edit/UONxA2?p=preview
-
这与 Angular 2 或其管道无关;
/^(\d+)?\.((\d+)(-(\d+))?)?$/doesn't match"12"。下次尝试一些基本的调试,你可以将它与 Angular 框架完全隔离。
标签: angular angular2-pipe