Aurelia - Converters



If you need to convert some values in Aurelia app, you can use converters instead of manually converting values to a desired format.

Convert Date

When we want to convert the default date value to some specific format, we can use momentJS library. This is a small library used for manipulating dates.

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

Let's create a new file converters.js. We will use this file to add converter specific code. Use the following command or create the file manually.

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

converter.js

Inside this file, we will import moment library and set DateFormatValueConverter to return only month, day and year values without additional data. Important thing to note is that Aurelia can recognize any class that ends with ValueConverter. This is why our class name is DateFormatValueConverter. This class will be registered as dateFormat and we can later use it inside view.

converters.js

import moment from 'moment';

export class DateFormatValueConverter {
   toView(value) {
      return moment(value).format('M/D/YYYY');
   }
}

In app.js, we will just use the current date. This will be our view-model.

app.js

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

We already discussed require in custom-elements chapter. The pipe symbol | is used to apply the converter. We are only using dateFormat since this is how Aurelia is registering DateFormatValueConverter.

app.html

<template>
   <require from = "./converters"></require>

   <h3>${currentDate | dateFormat}</h3>
</template>
Aurelia Converters Date

Convert Currency

This is an example of currency formatting. You will notice that the concept is the same as in the above example. First, we need to install numeral library from the command prompt.

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

The Converter will set the currency format.

converters.js

import numeral from 'numeral';

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

View-model will just generate a random number. We will use this as currency value and update it every second.

app.js

export class App {
   constructor() {
      this.update();
      setInterval(() => this.update(), 1000);
   }
   update() {
      this.myCurrency = Math.random() * 1000;
   }
}

Our view will show the randomly generated number transformed as a currency.

app.html

<template>
   <require from = "./converters"></require>

   <h3>${myCurrency | currencyFormat}</h3>
</template>
Aurelia Converters Currency
Advertisements