Conditional Rendering
Learn about the various methods for conditionally rendering content in Aurelia 2, with detailed explanations and examples.
Conditional rendering allows you to dynamically show or hide parts of your view based on your application's state. Aurelia 2 provides three primary directives for conditional rendering, each suited for different scenarios.
Quick Reference
if.bind
Simple true/false conditions
Adds/removes elements
Best for infrequent changes
show.bind
Toggle visibility
Hides/shows elements
Best for frequent changes
switch.bind
Multiple conditions
Adds/removes elements
Best for enum-like values
Using if.bind
if.bindThe if.bind directive conditionally adds or removes elements from the DOM based on a boolean expression. When the expression is false, Aurelia completely removes the element and its descendants, cleaning up resources, events, and custom elements.
Basic Usage
<div if.bind="isLoading">Loading...</div>
<div if.bind="user.isAuthenticated">Welcome back, ${user.name}!</div>If/Else Structures
Use else immediately after an if.bind element to create branching logic:
<div if.bind="user.isAuthenticated">
Welcome back, ${user.name}!
</div>
<div else>
Please log in to continue.
</div>Caching Behavior
By default, if.bind caches views and view models for performance. Disable caching when you need fresh instances:
When to Use: Use if.bind when elements change infrequently and you want to completely remove them from the DOM to save memory and improve performance.
Using show.bind
show.bindThe show.bind directive toggles element visibility without removing them from the DOM. This is equivalent to setting display: none in CSS.
Basic Usage
hide.bind (inverse of show.bind)
hide.bind (inverse of show.bind)hide is an alias of show with inverted logic:
This is equivalent to:
When to Use show.bind vs if.bind
Using switch.bind
switch.bindThe switch.bind directive handles multiple conditions elegantly, similar to a JavaScript switch statement. It's ideal for enum values or when you have several mutually exclusive conditions.
Basic Usage
Grouping Cases
Handle multiple values with a single case:
Fall-Through Behavior
Enable fall-through to show multiple cases:
Advanced Techniques
Dynamic Switch Expressions
Use computed expressions with switch.bind:
Conditional Slot Projection
Combine switch.bind with slots for dynamic content projection:
Nested Switches
Handle complex conditional logic with nested switches:
Performance Guidelines
Choosing the Right Directive
Frequent toggles: Use
show.bindto avoid DOM manipulation overheadInfrequent changes: Use
if.bindto remove elements and save memoryMultiple conditions: Use
switch.bindfor cleaner, more maintainable code
Optimization Tips
Important Restrictions
Case Usage Rules
The case attribute must be a direct child of switch.bind:
Default Case Placement
Place default-case as the last option for best practices:
Last updated
Was this helpful?