How to pass an action from template controller to Grand child component

I am quiet new Ember frame work. I am trying to pass an “action” from the controller to the grandchild component of the current template. But it fails for some reason. Could anyone let me know what am I missing here.

MainTemplate's Router Controller

export default class MainTemplateController extends Controller {

      field = "userId";

      @action
      save () {
        //save data
      }

}

MainTemplate.hbs
<ChildComponent @field={{this.field}} @save={{this.save}} /> 


ChildComponent.hbs 
<GrandChildComponent @field={{this.field}} @save={{this.save}} />


GrandChildComponent.hbs
<button @onClick={{action "doSomething" (readonly @field)}}>Save</button>

export default class GrandChildComponent extends Component {    
    @action
    doSomething(fieldName) {
        console.log(fieldName); // logs as "userId"
        console.log(this.args.save) // undefined
    }    
}

I think your problem is this line:

<GrandChildComponent @field={{this.field}} @save={{this.save}} />

It should look like this instead:

<GrandChildComponent @field={{@field}} @save={{@save}} />

console.log(this.args.save)

Would this console still have to be this.args.save OR can be this.save ?

It has to be this.args.save in a Glimmer component, but can be either in an Ember component. This is one the critical differences between the two. In a template, you should always prefer @save when referencing an argument passed in because it works correctly across both, as well as making the template clearer.

Thank you Chris. That worked.

1 Like