Dynamic composition is a crucial part of developing robust user interfaces in Aurelia. If you worked with the compose element in Aurelia 1, you might (or might not have) needed to obtain a reference to the composed view-model itself.
While Aurelia 2 keeps many things the same, how dynamic composition works is a little different. We have the new au-compose custom element, which allows us to achieve the dynamic composition of components, including passing data into them.
I am in the process of porting over an Aurelia 1 application, and it contains a wizard-based step form. The wizard acts as the containing element and queries the child step custom components, allowing specific methods inside of them to be called (validation callbacks and so on).
Now, in Aurelia 1, you could write something like this:
<template> <compose view-model="hello" model.bind="myModel" view-model.ref="composeRef"></compose> </template>
Using view-model.ref, you could access the composed view-model instance. In Aurelia 2, it’s not much different, except the referenced view-model is not the composed view-model.
<au-compose view-model.bind="hello" model.bind="myModel" view-model.ref="composeRef"></au-compose>
Inside of your view-model, which gets the composeRef value, you can access the composed view-model in the composition controller:
attached() { this.composedViewModel = this.composeRef.composition.controller.viewModel; }
The composition property on the provided reference is where the view-model and other associated values/properties for the composed custom element live.
I have created an issue for this on the Aurelia GitHub repository. There is a chance that this might be simplified to be more in line with how Aurelia v1 works. The outcome will either be the viewModel
property works like v1, or this behaviour will be better documented.
Aurelia users need to understand that several improvements have been made in Aurelia 2, which address some fundamental shortcomings in how v1 was designed. Aurelia 2 makes use of classes that it instantiates, opposed to the mess of strings and module resolution v1 used, which caused plenty of issues with bundlers and complicated implementing support for things like lazy loading and split bundling.
It would be good if you explained why this change was made, ie. the purpose of the breaking change and what benefit it brings (if any)?
@Kevin Frey
That’s a very good point. I’ve just added in some more text to the bottom and a link to a GitHub issue I have created. There is the chance that this behaviour might be slightly tweaked to work like v1 or just better documented. Part of the reason things like these aren’t 1:1 with Aurelia 1 is because in Aurelia 2 you don’t use strings for referencing components anymore, the router and dynamic composition are two things that come to mind which work on the premise of objects and classes being provided directly.