Search code examples
htmlaurelianumeral.js

Using Numeral.js from HTML in Aurelia


I have the following working Aurelia code:

total = 9000;
<div class="row pt-2">
  <div class="col-10 text-right">Amount is</div>
  <div class="col-2 text-right">${total}</div>
</div>

What I want to do is use the Numeral.js library in HTML to format the total variable from 9000 to 9000.00. This is what I have tried:

total = 9000;
<div class="row pt-2">
  <div class="col-10 text-right">Amount is</div>
  <div class="col-2 text-right">${numeral(${total}).format('0.00')}</div>
</div>

and the following:

total = 9000;
<div class="row pt-2">
  <div class="col-10 text-right">Amount is</div>
  <div class="col-2 text-right">numeral(${total}).format('0.00')</div>
</div>

but unfortunately, none have worked. I tried using the Numeral library in TypeScript and it works fine. I need this on the HTML though. I'm super responsive so don't hesitate to ask any questions.


Solution

  • Use a value converter to wrap the call to numeral.

    This is what your value converter will look like. You'll have to add the correct import statement to the file though.

    import numeral from 'numeral';
    
    export class CurrencyFormatValueConverter {
      toView(value, format = '0.00') {
        return numeral(value).format(format);
      }
    }
    

    Then you'll need to load the value converter in to your view using a require element.

    <require from="./path/to/file'></require>
    

    Then you can use it in your view.

    <div class="row pt-2">
      <div class="col-10 text-right">Amount is</div>
      <div class="col-2 text-right">${total | numeral }</div>
    </div> 
    

    or you can pass in a custom format as a parameter to override the default:

    <div class="row pt-2">
      <div class="col-10 text-right">Amount is</div>
      <div class="col-2 text-right">${total | numeral:'($0,0.00)' }</div>
    </div> 
    

    Incidentally, you should give our documentation a look, as it actually includes this exact value converter as one of its examples: https://aurelia.io/docs/binding/value-converters#value-converters