If/else In Aurelia Using The “else” Attribute

Last updated: December 11, 2017

Did you know Aurelia introduced an else attribute a while ago which allows you to do if/else statements in your views complete with support for animation?

If you have been working with Aurelia for more than a few months, then you probably have been working with if/else statements by using multiple if.bind attributes in your HTML or using a terniary inside of string interpolation curlies. But, the else attribute allows us to write cleaner HTML without the need for multiple if statements doing the inverse of one another.

Not only does the else attribute simplify template control syntax, it also supports animation via the Aurelia Animator, thanks to the swap binding parameter added to if you can choose how your else element moves into place with the existing if.

Let’s start with a simple example:

<div if.bind="myCondition">This is truthy</div>
<div else>This is falsy</div>

This is the else attribute in use. It adds an inverse if.bind to your DIV based on the previous condition.

Previously you might have written that like this:

<div if.bind="myCondition">This is truthy</div>
<div if.bind="!myCondition">This is falsy</div>

This isn’t completely horrible, but else is arguably easier to write and look at. You want to avoid bloating your views at all costs. Plus, animating the transition between those two elements would be difficult and not possible with Aurelia out-of-the-box.

If/else with animation:

This is my favourite thing about using if and else together: animation. The if binding supports a binding parameter (we mentioned above) called swap which dictates how the if and else coordinate with one another when animation.

Supported values for swap are:

  • before – Animation is triggered before element is removed
  • with – Animation smoothly syncs up with both elements
  • after Animation is triggered after if condition

One thing you need to keep in mind is you need to add au-animate to the element that has the else attribute. The example below showcases how you can use swap with if and else to animate the change.

<div if="condition.bind: myCondition; swap: with">Truthy :)</div>
<div else class="au-animate">Falsy :(</div>

If you want to change the animation mode, just replace with in the above example with any of the valid options.


You might be tempted to try different combinations of if and else but the else attribute is intentionally limited. There aren’t too many caveats, just a couple you need to be aware of to avoid frustration.

  • You cannot chain else attributes ie. Multiple else statements.
  • The else attribute cannot be used with if on the same line. This will not work: else if.bind="condition"
  • The element containing the else attribute needs to come after the element with if



Leave a Reply

Your email address will not be published. Required fields are marked *