Aurelia Converters

In the Last article, we learned Aurelia Events. In this article we will discuss what is Aurelia Converters. Rather than manually converting the values, Aurelia has what we call converters.

Converting Date

A small library called momentJS can be used to convert and manipulate a default date into a specific format.

C:\Users\username\Desktop\aureliaApp>jspm install moment

Next, to add a converter on a specific code, use the following code to create the file manually.

C:\Users\username\Desktop\aureliaApp>touch converters.js

Inside the converter.js file, moment library should be imported and DateFormatValueConverter is set only to return month, day and year and not anything else. Do note that Aurelia can acknowledge any class that ends with ValueConverter. Thus DateFormatValueConverter. The class was registered as dateFormat to use it later in the view.

converter.js

import moment from ‘moment’;
export class DateFormatValueConverter {
  toView(value) {
     return moment(value).format(‘M/D/YYYY’);
  }
}

app.js

export class App {

  constructor() {
     this.currentDate = new Date();
  }
}

By now, the term require should be familiar as seen on the custom elements chapter. The | pipe symbol is used to apply the conversion. dateFormat is used by Aurelia to register DateFormatValueConverter.

app.html

<template>

  <require from = “./converters”></require>

  <h3>${currentDate | dateFormat}</h3>
</template>

Converting Currency

In currency conversion, the concept is same as the above. First, numeral library should be installed from the command prompt.

C:\Users\username\Desktop\aureliaApp>jspm install numeral

converter.js

import numeral from ‘numeral’;

export class CurrencyFormatValueConverter {
  toView(value) {
     return numeral(value).format(‘($0,0.00)’);
  }
}

The currency format will be set.

export class App {

  constructor() {
     this.update();
     setInterval(() => this.update(), 1000);
  }

  update() {
     this.myCurrency = Math.random() * 1000;
  }
}

A random number will be generated at the view-model. It will be used as the currency value while it is updated every second.

<template>
  <require from = “./converters”></require>

  <h3>${myCurrency | currencyFormat}</h3>
</template>

Then the view will show the generated number as the transformed currency.

On the next tutorial, we will learn about Aurelia Animations.

Subscribe Now and Upgrade Your Skills Today!
Sign up now and have the latest tech tutorials delivered straight to your mailbox.

PLUS: Get exclusive member-only discounts (up to 80% OFF!!) on our top tech courses in Udemy!
We hate spam. Your email address will not be sold or shared with anyone else.