The best option for me was the famous https://www.npmjs.com/package/numeral . (it works with the same moment.js logic)
To install it: npm i numeral@2.0.6 and with types npm i --save-dev @types/numeral@0.0.22
In your ts file you can use the following:
`R$ ${numeral(<your-model-value>).value().toLocaleString()}`
For an HTML template, you can create a Pipe as follows:
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(); } }
In addition, for currency (and locales), a good strategy is to use the ng2-currency-mask package for macros in HTML (but in ts files that may need to "translate" the anchored value in the model using numeral before saving the model object.
Using ng2-currency-mask in an HTML template:
<input [(ngModel)]="model.value" [options]="{ prefix: 'R$ ', thousands: '.', decimal: ',' }" allowNegative="false" currencyMask>
And on ts before saving the model:
if(this.model.value) this.model.value = numeral(this.model.value).value();
https://github.com/cesarrew/ng2-currency-mask
Richard Lee
source share