Reusable components in Aurelia, i.e. templates that get fed some of their (dynamic) content by the parent

I realize that Aurelia is meant to be a “simple” framework.
But still, I’m wondering what would be the best way of achieving this.

Imagine that you want to have a List component (i.e., template) that is completely generic and reusable. Its only purpose is to display some items arranged in a vertical layout, with a scroll bar, a fixed spacing between each item, and some padding.

Now, you don’t want the list’s items to be clearly defined. They could be literally anything. Maybe the list item is a template meant to display an image. Maybe the list item is a template that’s a clickable button. Maybe the list item is an elaborate template with an icon, a text, a subtext, action buttons on the side, etc.
Again: the list items could be any kind of template.

In React, they have implemented this: you can pass an entire component (Aurelia template), or even an array of components, as a parameter to another template. For example, I would pass the array of item components to the list component and call it a day.

The list would not need to have a list of all item titles, all item icons, all item buttons, etc. The items are provided by the parent, ready to be rendered. all the list has to do is to display them.

The closest thing I found in Aurelia is the concept of slots, but it is clearly stated that you cannot pass “dynamic” Aurelia content into the slots. All you can do is pass down regular HTML (even though, of course, there’s a small layer of fanciness, with the “fallback slots”).

So, what would be the best practice to mutualize as much code as possible in order to render a list of items without needing to have a dedicated list component (template) for each type of list item?

I think I have some kind of answer here : https://codesandbox.io/p/sandbox/kw10xw295v?file=%2Fsrc%2Fapp.html

the solution would be the “compose” mechanism.

It’s more along the line of polymorphism, where:

  • each item component has its own view-model (i.e. its html and code-behind). That’s a given in Aurelia, so any component can be swapped with any other component**. Check!**
  • each item component is fed with an arbitrary “model” object, appropriate to its type. Since it’s just a Javascript object containing the data to render, you can give anything you want (provided the view model knows how to render it). Check!

I did something similar recently where I wanted to have a generic dialog component that could host any component. The dialog would essentially be told which component to render. Hopefully this helps: V2 Dialog Example - #4 by davidsk

Thanks. Yes, that’s the general idea.

2 Likes