EmberJS - Actions



The {{action}} helper class is used to make the HTML element clickable and action will be forwarded to the application when the user clicks an event.

Syntax

<button {{action 'action-name'}}>Click</button>

The above code adds the button Click to your application in which the action will be forwarded to the specified action method when a user clicks the button.

The following table lists down the action events of actions along with their description −

S.No. Action Events & Description
1 Action Parameters

The arguments can be passed to an action handler with the help of {{action}} helper.

2 Specifying the Type of Event

The alternative event can be specified on {{action}} helper by using the on option.

3 Allowing Modifier Keys

You can allow modifier keys along with the {{action}} helper by using the allowedKeys option.

4 Modifying Action's first Parameter

You can modify the action's first parameter by specifying a value option for the {{action}} helper.

Example

The example given below shows the usage of {{action}} helper to make the HTML element clickable and action will be forwarded to the specified action method. Create a component with name post-action by using the following command −

ember g component post-action

Open the post-action.js file created under app/component/ and add the following code −

import Ember from 'ember';

export default Ember.Component.extend ({
   actions: {
      toggleBody() {
         this.toggleProperty('isShowingBody');
      }
   }
});

Open the file post-action.hbs file created under app/templates/ with the following code −

<h1>Hello</h1><h3><button {{action "toggleBody"}}>{{title}}Toggle</button></h3>
{{#if isShowingBody}}
   <h2>Welcome To Tutorials Point</h2>
{{/if}}
{{yield}}

In the index.hbs file, copy the below code which is created under app/templates/

{{post-action}}
{{outlet}}

Output

Run the ember server; you will receive the following output −

Ember.js Template Actions

When you click on the Toggle button, it will display the following text from the template file −

Ember.js Template Actions
emberjs_template.htm
Advertisements