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.bind
The 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
If/Else Structures
Use else
immediately after an if.bind
element to create branching logic:
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.bind
The show.bind
directive toggles element visibility without removing them from the DOM. This is equivalent to setting display: none
in CSS.
Basic Usage
When to Use show.bind vs if.bind
Using switch.bind
switch.bind
The 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.bind
to avoid DOM manipulation overheadInfrequent changes: Use
if.bind
to remove elements and save memoryMultiple conditions: Use
switch.bind
for 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?