Monday, November 16, 2026
HomeJavaScriptTen Aurelia 2 Options You've got In all probability By no means...

Ten Aurelia 2 Options You’ve got In all probability By no means Used


Most Aurelia apps get by on worth.bind, click on.set off, if.bind and repeat.for. That covers so much, however Aurelia 2 ships with loads of smaller options that don’t get a lot consideration, and each replaces code you’d in any other case write your self.

Listed here are ten of them. Every little thing under works in RC.2 with no further packages or registration.

1. Counting with repeat.for

repeat.for doesn’t want an array. Give it a quantity and it counts from zero:

<span
  repeat.for="i of 5"
  class="star ${i < score ? 'crammed' : ''}">★</span>

With score = 3, you get 5 stars and the primary three are crammed. Skeleton loaders, pagination dots and fixed-size grids all work the identical manner, with no Array.from({ size: 5 }) in your view mannequin.

2. $earlier in a repeat

You most likely know $index, $first and $final. There’s additionally $earlier, which provides you the merchandise from the iteration earlier than. It’s the straightforward manner so as to add group headings to a sorted checklist:

<template repeat.for="message of messages">
  <h3 if.bind="message.day !== $earlier?.day">${message.day}</h3>
  <p>${message.textual content}</p>
</template>

A heading solely renders when the day adjustments. The primary merchandise has no earlier merchandise, so the ?. handles that case. It stays appropriate because the checklist adjustments, too: insert a message within the center and the headings round it replace.

3. <let> for template variables

When a template retains repeating the identical expression, give it a reputation with <let>:

<let subtotal.bind="gadgets.cut back((sum, merchandise) => sum + merchandise.value * merchandise.amount, 0)"></let>

<p>Subtotal: ${subtotal}</p>
<p if.bind="subtotal >= 100">You've got obtained free transport.</p>

Kebab-case names turn out to be camelCase, so <let full-name.bind="..."> offers you fullName. The worth updates when something it relies on adjustments, and it belongs to the template, not your view mannequin. Should you do need it on the view mannequin, add to-binding-context to the factor.

4. promise.bind

Loading states often imply an isLoading flag, an error property and a attempt/catch/lastly. promise.bind does all of that within the template:

<div promise.bind="profile">
  <p pending>Loading…</p>
  <p then="consumer">Whats up, ${consumer.identify}</p>
  <p catch="error">Could not load your profile: ${error.message}</p>
</div>
export class ProfilePage {
  profile = fetch('/api/me').then(r => r.json());
}

Solely one of many three renders at a time. Assign a brand new promise to profile (for a retry button, say) and the template goes again to pending till it settles. If an older promise settles after you’ve changed it, its result’s ignored.

5. portal

Tooltips, dropdowns and modals have a behavior of getting clipped by a guardian with overflow: hidden or trapped below a sibling’s z-index. portal renders a component someplace else within the DOM whereas it stays sure to the element that declared it:

<div class="tooltip" portal if.bind="showTooltip">
  ${tooltipText}
</div>

With no worth, the factor strikes to the top of <physique>. Give it a selector to place it someplace particular:

<div portal="#modals">...</div>

The bindings nonetheless use your element’s scope, so ${tooltipText} and any occasion handlers work as if the factor by no means moved.

6. Two-way focus.bind

Focus is generally one thing you set imperatively, with a ref and a name to .focus(). The focus attribute binds it like another worth, and it’s two-way by default:

<enter focus.bind="searchFocused" worth.bind="question">
<p present.bind="searchFocused">Press Enter to go looking</p>

Set searchFocused = true and the enter will get focus. When the consumer clicks or tabs away, searchFocused goes again to false. That makes it straightforward to focus a discipline when a panel opens, or to indicate hints solely whereas the consumer is within the discipline.

7. present.bind and conceal.bind

if.bind provides and removes parts. present.bind solely toggles visibility:

<div present.bind="isExpanded">...</div>
<div conceal.bind="isExpanded">...</div>

conceal.bind is the inverse, which saves you writing present.bind="!isExpanded". Use present when one thing toggles usually or holds state you wish to maintain, like a half-filled kind in a collapsed panel or a video that ought to maintain its place. Use if when the content material is pricey to maintain round or shouldn’t exist in any respect till it’s wanted.

8. Occasion modifiers

Occasion bindings take modifiers after a colon, which covers most of what you’d in any other case examine by hand within the handler:

<!-- solely on Enter -->
<enter keydown.set off:enter="addTodo()">

<!-- Ctrl+Enter to ship, plain Enter nonetheless provides a brand new line -->
<textarea keydown.set off:ctrl+enter="ship()"></textarea>

<!-- name preventDefault() for you -->
<kind submit.set off:stop="save()">...</kind>

<!-- shift-click to pick a variety -->
<li click on.set off:shift="selectRange(merchandise)">${merchandise.identify}</li>

stop and cease name preventDefault() and stopPropagation(). ctrl, alt, shift and meta examine modifier keys, and left, center and proper examine mouse buttons. You possibly can mix them with +, so keydown.set off:ctrl+shift+enter works too.

9. & self

A modal backdrop ought to shut the modal when it’s clicked, however not when the clicking lands on the dialog inside it. Usually meaning evaluating occasion.goal and occasion.currentTarget. The self binding conduct does it for you:

<div class="backdrop" click on.set off="shut() & self">
  <div class="dialog">
    <button>Contained in the dialog</button>
  </div>
</div>

The handler solely runs when the clicking goal is the factor with the binding, so clicks that bubble up from the dialog are ignored.

10. & sign

Some values change with none property altering. Relative instances are the basic case: “simply now” ought to turn out to be “5 min in the past” although postedAt hasn’t modified. Bindings with & sign replace everytime you ship that sign. Right here timeAgo is a price converter that turns a date into textual content like “5 min in the past”:

<span>$ timeAgo & sign:'clock'</span>
import { ISignaler, resolve } from 'aurelia';

export class CommentList {
  personal readonly signaler = resolve(ISignaler);
  personal timer?: ReturnType<typeof setInterval>;

  hooked up() {
    this.timer = setInterval(() => this.signaler.dispatchSignal('clock'), 60_000);
  }

  indifferent() {
    clearInterval(this.timer);
  }
}

Each binding that listens for clock updates as soon as a minute, wherever within the app. Indicators are additionally useful after a language or forex change, when each formatted worth on the web page must replace directly.

That’s ten

There are extra the place these got here from. & updateTrigger:'blur', & attr, change.bind and the unfold syntax for bindables would all slot in a put up like this. When you’ve got a favorite small function that ought to have made the checklist, inform us on
Discord
.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments