I believe the confusion here is when you use enhance
to enhance custom elements, the component
property is the root controller. Think of it as similar to how <my-app>
is the root component in a default Aurelia 2 app scaffolded.
So while you think passing in your component registered via DI to component
is what renders it, that’s actually the root component for the host
property.
I have created an example here to highlight this: aurelia-enhance-demo - StackBlitz
In index.html
you will see this HTML:
<my-app></my-app>
<div id="enhance-me"><my-component name.bind></my-component></div>
Notice on my-component
I have a bindable called name? Yet when you run the code linked, it shows Aurelia as a value despite the fact my-component.ts
doesn’t have a default value (it’s an empty string):
import { bindable } from 'aurelia';
export class MyComponent {
@bindable name = '';
}
So, where does it come from? It comes from our host root component.
In my-app.ts
I have the following:
attached() {
const element = document.getElementById('enhance-me');
this.au.enhance({
host: element,
component: MyHost,
});
}
In main.ts
I already registered my-component
, but you’ll notice I am passing MyHost
instead.
Going into my-host
and you’ll see where the name value comes from:
import { customElement } from 'aurelia';
@customElement({
name: 'my-host',
template: null,
})
export class MyHost {
name = 'Aurelia';
}
So, this becomes the parent for all enhanced children. But, it’s worth noting (as the docs correctly show), you don’t need to pass any root component, you can just specify an empty object {}
to the component and it will enhance just fine.
attached() {
const element = document.getElementById('enhance-me');
this.au.enhance({
host: element,
component:{},
});
}
Provided your custom element being enhanced is globally registered in DI, it’ll still render.
For non-custom element enhancement, the component
becomes the view-model.
So in your my-app.ts
you could do something like this as an example:
import { IAurelia, resolve } from 'aurelia';
export class MyApp {
private au = resolve(IAurelia);
attached() {
const element = document.getElementById('enhance-me');
element.innerHTML = '<ul><li repeat.for="fruit of fuits">${fruit}</li></ul>';
this.au.enhance({
host: element,
component:{
fruits: ['Apple', 'Mango', 'Banana', 'Grapes']
},
});
}
}
And if you ran that, you would see four bullet points with our fruit being rendered.