Value converters (pipes)

Master Aurelia's value converters for powerful data transformation. Learn formatting, localization, custom converters, performance optimization, and real-world patterns.

Value converters are a powerful feature in Aurelia 2 that transform data as it flows between your view model and view. They enable clean separation of concerns by moving data formatting logic out of your view models while keeping templates readable and maintainable.

Overview

Value converters excel at:

  • Data formatting - dates, numbers, currencies, text transformations

  • Localization - dynamic content based on user locale

  • Display logic - conditional formatting without cluttering view models

  • Two-way transformations - handling both display and input conversion

  • Reactive updates - automatic re-evaluation on global state changes

  • Performance optimization - caching expensive transformations

Key Advantages

  • Pure functions - predictable, testable transformations

  • Reusable - use the same converter across multiple components

  • Composable - chain multiple converters for complex transformations

  • Framework integration - seamless integration with Aurelia's binding system

  • TypeScript support - full type safety and intellisense

Data Flow

Converters work in two directions:

  • toView: Prepares model data for display.

  • fromView: Adjusts view data before updating the model (useful with two-way binding).

Both methods receive the primary value as the first argument, with any extra arguments used as configuration.

Example Methods

Basic Usage

Template Syntax

Use the pipe symbol (|) to apply a converter in templates:

Simple Converter Example

Usage in template:

Parameter Passing

Converters accept parameters using colons (:) for configuration:

Static Parameters

Bound Parameters

Object Parameters

Chaining Converters

Chain multiple converters for complex transformations:

Chain execution order: Left to right, where each converter receives the output of the previous one.

Advanced Template Patterns

Conditional Formatting

Dynamic Parameter Selection

Nested Object Access

Receiving the Caller Context

By default, value converters receive only the value to transform and any configuration parameters. In some advanced scenarios, you may need to know more about the binding or calling context that invoked the converter—for example, to adjust the transformation based on the host element, attributes, or other binding-specific state.

Aurelia 2 provides an opt-in mechanism to receive the binding instance itself as an additional parameter. To enable this feature:

  1. Add withContext: true to your value converter class:

Then use your converter in templates as usual:

At runtime, Aurelia will detect withContext: true in the value converter and pass the binding instance as the second parameter. Depending on how the converter is used:

  • Property Binding (foo.bind or attr.bind): the caller is a PropertyBinding instance

  • Interpolation (${ } with converters): the caller is an InterpolationPartBinding instance

  • Other Bindings: the caller corresponds to the specific binding type in use

Common Use Cases

  • Logging or debugging which binding invoked the converter

  • Applying different formatting based on binding context

  • Accessing binding metadata or context not available through standard converter parameters

Use this feature sparingly, only when you truly need insights into the calling context. For most formatting scenarios, simple converter parameters and camelCase converter names are sufficient.

Accessing the View Model and Binding Context

Once withContext: true is enabled, your converter receives a caller parameter with direct access to the view model and binding information:

Caller Context Properties

  • caller.source: The view model instance of the component where the converter is used

    • This is the actual component class instance with all its properties and methods

    • Allows converters to access component state, computed properties, and methods

    • Always available when converter is used within a component

  • caller.binding: The binding instance that invoked the converter

    • Contains binding-specific information and metadata

    • Useful for debugging or advanced binding manipulation

    • Type varies: PropertyBinding, InterpolationPartBinding, etc.

Real-World Example: User Permission Converter

Usage in template:

Registration Patterns

Aurelia 2 provides flexible registration patterns for different use cases and architectural preferences.

The most common and straightforward approach:

2. Configuration Object Registration

For advanced options including aliases:

Usage with aliases:

3. Static Definition

Using the static $au property (alternative registration approach):

4. Manual Registration

For dynamic or runtime registration scenarios:

5. Local vs Global Registration

Global Registration (Application-wide)

Local Registration (Component-specific)

Scoped Registration (Feature Module)

6. Conditional Registration

Register converters based on environment or feature flags:

Best Practices for Registration

  1. Use decorators for most cases - Simple and straightforward

  2. Group related converters - Organize by feature or domain

  3. Consider lazy loading - Register heavy converters only when needed

  4. Document aliases - Make alternative names clear to team members

  5. Avoid global pollution - Use local registration for component-specific logic

Creating Custom Value Converters

Custom value converters are classes that implement transformation logic. They provide a clean way to handle data formatting throughout your application.

Basic Structure

TypeScript Best Practices

Strong Typing

Generic Converters

Bidirectional Converters (Two-Way Binding)

Perfect for form inputs that need both display formatting and input parsing:

Phone Number Formatter

Usage with two-way binding:

Credit Card Formatter

Error Handling and Validation

Performance Optimization

Memoized Converter

Utility Converters

Null-Safe Converter

Debug Converter

Usage:

Signals-Based Reactivity

Value converters can automatically re-evaluate when specific signals are dispatched, perfect for locale changes, theme updates, or global state changes.

To trigger re-evaluation from anywhere in your app:

Now all localeDate converters automatically update when the locale changes, without needing to manually refresh bindings.

Built-in Signal-Aware Converters

Aurelia 2 includes several built-in converters that leverage signals:

Built-in Value Converters

Aurelia 2 includes several built-in converters ready for use:

Sanitize Converter

Aurelia 2 includes a sanitize converter, but it requires you to provide your own sanitizer implementation:

Then you can use the sanitize converter:

Note: The built-in sanitize converter throws an error by default. You must provide your own ISanitizer implementation for it to work.

I18n Converters (when @aurelia/i18n is installed)

Advanced Configuration Options

Date Formatter Example

This converter formats dates based on locale:

Import it in your view:

Usage examples:

View this in action on StackBlitz.

Real-World Converter Examples

File Size Converter

Convert bytes to human-readable file sizes:

Relative Time Converter

Display time relative to now (e.g., "2 hours ago"):

Truncate with Tooltip Converter

Truncate text with full text available on hover:

Markdown to HTML Converter

Convert markdown text to HTML (using marked library):

Search Highlight Converter

Highlight search terms in text:

Sort Array Converter

Sort arrays by property or custom function:

Color Converter

Convert between color formats:

Performance Optimization

Caching Strategies

Implement intelligent caching for expensive operations:

Lazy Evaluation

Defer expensive operations until actually needed:

Memory Management

Prevent memory leaks in converters:

Benchmark and Profile

Use performance measurement for optimization:

Best Practices

1. Design Principles

Single Responsibility

Pure Functions

2. TypeScript Integration

Strong Typing

Generic Constraints

3. Error Handling

Graceful Degradation

4. Testing Strategies

Unit Testing

Troubleshooting Common Issues

Issue: Converter Not Found

Problem: Template shows error "No ValueConverter named 'myConverter' was found"

Solutions:

  1. Import the converter:

  2. Check decorator name:

  3. Global registration:

Issue: Performance Problems

Problem: Page becomes slow with converters in loops

Solutions:

  1. Implement caching:

  2. Use signals for global updates:

  3. Optimize template usage:

Issue: Context Access Not Working

Problem: caller parameter is undefined in toView

Solutions:

  1. Enable context access:

  2. Correct parameter order:

Issue: Signals Not Triggering

Problem: Converter doesn't update when signal is dispatched

Solutions:

  1. Declare signals array:

  2. Dispatch signals correctly:

Built-in Converters Reference

Core Converters

Converter
Purpose
Package
Parameters

sanitize

HTML sanitization

@aurelia/runtime-html

None (requires ISanitizer implementation)

I18n Converters (when @aurelia/i18n is installed)

Converter
Purpose
Parameters
Example

t

Translation

key, options

`${'hello'

df

Date formatting

options

`${date

nf

Number formatting

options

`${price

rt

Relative time

None

`${timestamp

Usage Examples

Summary

Value converters in Aurelia 2 provide a powerful, flexible system for data transformation:

  • Bidirectional support - Handle both display formatting and input parsing

  • Signal-based reactivity - Automatic updates on global state changes

  • Context awareness - Access binding context when needed

  • Performance optimization - Built-in caching and lazy evaluation support

  • Type safety - Full TypeScript support with strong typing

  • Flexible registration - Multiple registration patterns for different needs

  • Extensibility - Easy to create custom converters for specific requirements

Use value converters to keep your templates clean and maintainable while providing rich data formatting capabilities throughout your application.

Last updated

Was this helpful?