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
else together: animation. The
if binding supports a binding parameter (we mentioned above) called
swap which dictates how the
else coordinate with one another when animation.
Supported values for
before– Animation is triggered before element is removed
with– Animation smoothly syncs up with both elements
afterAnimation is triggered after
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
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
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
elseattributes ie. Multiple
elseattribute cannot be used with
ifon the same line. This will not work:
- The element containing the
elseattribute needs to come after the element with