Working with au-slot in Aurelia 2: Creating a Repeater with Replaceable Components

Aurelia 2 has some awesome templating features that make creating dynamic and replaceable components a breeze. One of these features is the au-slot tag. This magic tag, combined with expose.bind and repeaters brings about a new level of control and flexibility for developers to create customizable components.

In Aurelia 2 there are two types of slots: and – the element is only for Shadow DOM-enabled components, whereas the element is more akin to replaceable parts in Aurelia 1 (it’s what they are now in v2).

Let’s see how we can use these features to create replaceable components within repeaters.

Exposing the Surrounding Scope with

One interesting aspect of is that it exposes the immediate surrounding scope by default. This default behaviour is handy because it saves you from manually exposing all necessary variables one by one. However, what if we want to expose a different scope or specific data set? That’s where expose.bind comes into play.

With expose.bind, we can explicitly control what data we want to expose within the . Whatever object is bound to expose.bind will be available as $host on the consumer side. This feature allows us to manipulate the exposed data within the slot conveniently.

Showcase: The Show-Products Component

For instance, let’s look at a component called show-products, used in an e-commerce application. Here’s the HTML code for it:

In the tag, expose.bind="{ $index, product }" exposes the index and the product data from each repetition. On the consumer side, we can access these data using the $host keyword.

Override and Customization: The Power of Replaceable Components

This is where the true power of shines – its ability to enable replaceable components. Using a , we can override the default implementation to provide our own component.

Here, we define a component inline called custom-product-card:

In this code, the custom-product-card component replaces the default product-card. The exposed product data from the show-products component can be accessed with $host.product.

Conclusion: Embrace the Flexibility

The tag, paired with expose.bind and repeaters represent a powerful toolset for front-end developers using Aurelia 2. It simplifies the creation of dynamic, replaceable components while maintaining a clean, understandable structure.

Whether you’re developing an e-commerce application or any application with dynamic content and replaceable components, Aurelia 2 is equipped to make your job easier and your code more robust.

And that, fellow coders, is the magic of combined with expose.bind and repeaters. Go forth and code flexibly! 🚀