0





9

Advertisement

I want to call a child component's function from its parent. I have a way to do it, but I want to know if I'm missing a better way.

From Ashley Grant's blog post about accessing a custom element's viewModel from a custom attribute, I see that Aurelia adds au to the element and you can access the viewModel through that. So, if I add a nested component with a ref, like this:

<template>
    <nested-element ref="childElement"></nested-element>
</template>

I can call a function on it like this:

this.childElement.au.controller.viewModel.someFunction();

This feels roundabout. I was hoping I would be able to access a nested element's viewModel through the parameters to a hook that the parent implements, such as created(owningView, myView) but I can't find a path to it.

Have I missed a better way?

Edit: I forgot to add that I need a return value from the function I'm calling, so having access to the viewmodel itself is preferable

Question author Mgiesa | Source

Advertisement


0


ref gives you the element. view-model.ref gives you the element's view model.

<template>
    <nested-element view-model.ref="childViewModel"></nested-element>
</template>

Call it like this in the parent view-model:

this.childViewModel.someFunction();
Answer author Jeff-g