The best option for me was the famous https://www.npmjs.com/package/numeral package. (he works with same logical of the moment.js
)
To install it: npm i [email protected]
and with types npm i --save-dev @types/[email protected]
At your ts
file you can use as follow:
`R$ ${numeral(<your-model-value>).value().toLocaleString()}`
For HTML template you can create a Pipe
like this:
import {Pipe, PipeTransform} from '@angular/core';
import * as numeral from 'numeral';
@Pipe({
name: 'numberLocale'
})
export class NumberLocalePipe implements PipeTransform {
transform(value: any, args?: any): any {
const numeralNumber = numeral(value);
return numeralNumber.value().toLocaleString();
}
}
Additionally, for currency (and locales) a good strategy is use the package ng2-currency-mask
for currency masks in HTML (but on ts
files you may should "translate" the binded value in the model with numeral
before save your model object.
Using ng2-currency-mask
on HTML Template:
<input [(ngModel)]="model.value"
[options]="{ prefix: 'R$ ', thousands: '.', decimal: ',' }"
allowNegative="false" currencyMask>
And on ts
before save the model:
if(this.model.value)
this.model.value = numeral(this.model.value).value();
https://github.com/cesarrew/ng2-currency-mask