When I first started looking at Aurelia one thing which appeared to be missing at first glance was the ability to easily apply filtering to a table. Fortunately we can implement this with minimal effort using Aurelia Value converters.
Aurelia Value Converters
Aurelia Value Converters are a class responsible for taking the data in the view-model and making it suitable for presentation in the view. The most basic example of this is a date filter. Instead of manually formatting the date in the view-model and storing it in a different property for presentation, or applying a format function in the view itself, we can pipe the date through a value converter to have it display in the format we want.
For example (example sourced from the Aurelia Blog):
This code is importing the momentjs library. It then provides a hook function called toView which translates the value piped into the value converter into a string formatted presentation suitable for the view. What I didn’t realise when I initially looked into value converters was how flexible they are. This flexibility allows us to do a lot more interesting things than simple formatting.
We’ll now build a filterable table using Bootstrap styling with value converters.
Firstly we’ll get the most basic thing on the page rendering by stamping out each of the raw todo items in a table:
Cleaning up the table
There are a number of improvements that we can make to this table, but let’s start by a adding value converter. We’ll apply a date format value converter to the created at column to improve readability. We’ll also add a class binding expression, and a check-box to allow us to toggle complete/incomplete items, and quickly view which items are complete:
Adding the table filter
Once we reach a certain todo-list size it becomes convenient to be able to quickly filter the list based on the text of the todo items. We can achieve this with the introduction of another value converter:
This value converter takes two parameters:
- searchTerm: The view-model property we wish to filter the table by.
- filterFunc: The comparison function used to determine whether a particular row matches the given search criteria.
We’ll also need to make some adjustments to our view-model to support filtering:
And make the corresponding adjustments in our view to take advantage of the new value-converter:
With very little effort we’ve been able to implement a generic filter pipe that we can use to filter client side data in a table (albeit a very naive one). Value Converters can also be used to implement sorting, paging etc, and are a vital part of the Aurelia tool-box.