How to access child component from parent component in Ember

574 views Asked by At

The concept is fairly simple.

Assume I have a child component with its own separate js and hbs. Child-component.hbs =>

<Button options = {{listOptions}} selected={{selectedOption}}
> Submit <Button

Child-component.js

listOptions =[{id: 124, name: 'Mywork'}
selected => performing an action after getting the value from hbs selection.

Now I'm importing this into another component Main-component.hbs like this

<ChildComponent />

This is rendering as expected with options and all, but based on the selectedOption I want to do something in my main component. Handling the action in the Main-component is not an option for me as its not what I was told to do. Is it possible to access selectedOption from the main-component? Kindly help.

Please note that I want to achieve this in Octane version.

1

There are 1 answers

0
NullVoxPopuli On

the only way to do this is to specifically pass a reference from the parent to the child, and have the child invoke some function on the parent (because, in rendering, data only flows down by default ("data down, actions/functions up"))

Example:

class Parent {
  foo(child) {
    // do something with the child
  }
}
<Child @foo={{this.foo}} />

// ------------------

class Child { }
{{ (@foo this) }}

Note that this is an "effect", and effects are generally a code-smell (derived data should be used whenever possible)