Call from component to controller in ember version 4.8

how to call a controller action from component class version 4.8

since controllers may not be instantiated by the time your component calls the action, it’ll be safer to extract the functionality to a service and call that service-action from both the controller and the component.

ember g service my-service
// app/services/my-service.js

export default class MyService extends Service {
  myAction = () => {}
}
// app/controllers/my-controller.js

export default class MyController extends Controller {
  @service myService;

  localAction = () => this.myService.myAction();
}
// app/components/some-component.js
export default class SomeComponent extends Component {
  @service myService;

  localAction = () => this.myService.myAction();
}
2 Likes

@NullVoxPopuli’s answer is great assuming that the function you want to call is not specific to the controller. If it is, you should pass it to the component on invocation:

// app/controllers/my-controller.js

import { action }  from '@ember/object';

export default class MyController extends Controller {
  @action
  doSomething() {
    // do something fancy
  }
}
{{! /app/templates/my-template.hbs }}

<SomeComponent @onClick={{this.doSomething}} />
{{! /app/component/some-component.hbs }}

<button {{on "click" @onClick}}>
  click me
</button>

The same pattern works for calling functions in a component passed in by another component.

1 Like