How to add `action` to component element in ember.js?

Member

by lew , in category: Javascript , a month ago

How to add `action` to component element in ember.js?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by arnoldo.moen , a month ago

@lew 

To add an action to a component element in Ember.js, you can define the action in the component's JavaScript file and then bind it to the element in the component's template file.


Here's an example of how you can add an action to a button element in a component:

  1. Define the action in the component's JavaScript file:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
// app/components/my-component.js
import Component from '@glimmer/component';
import { action } from '@ember/object';

export default class MyComponent extends Component {
  @action
  handleClick() {
    alert('Button clicked!');
  }
}


  1. Add the action to the button element in the component's template file:
1
2
<!-- app/components/my-component.hbs -->
<button {{on "click" this.handleClick}}>Click me</button>


In this example, when the button in the component is clicked, the handleClick action defined in the MyComponent class will be triggered, displaying an alert with the message "Button clicked!".


Remember to import action from @ember/object at the top of the component's JavaScript file in order to define the action correctly.