jdixon04
jdixon04

Reputation: 1595

Accessing Parent Properties in Nested Components

In anticipation of Routable Components coming soon, I'm attempting to use Components wherever possible in my Ember 2.0 application. I'm running into a confusing issue where I cannot access the parent component's properties from the template when provided in block form. It may be very well that this isn't possible, but wanted to be sure. Here's an example:

Template:

// templates/approvals.hbs
{{#x-secure/schedule/approvals}}

  {{#x-secure/layout/full sectionTitle=sectionTitle sectionDescription=sectionDescription}}
    ...
  {{/x-secure/layout/full}}

{{/x-secure/schedule/approvals}}

Component Template:

// templates/components/schedule/approvals.hbs
{{yield}}

Component:

// components/schedule/approvals.js
import Ember from 'ember';

export default Ember.Component.extend({

  /////////////////////////////////////
  // PROPERTIES
  /////////////////////////////////////

  sectionTitle: 'Scheduling: Approvals',
  sectionDescription: 'Lots of magical , fanstastic stuff.'

});

The issue I'm having is that I'm unable to access sectionTitle and sectionDescription from the parent component (approvals) and pass it into the layout/full component. However, if I remove code from the block of the component and move it to the templates/components/schedule/approvals.hbs template, it works as expected. Is it just not possible to access a parent component's properties from the block form of a component?

Thanks!

Upvotes: 0

Views: 401

Answers (1)

spectras
spectras

Reputation: 13562

It is not possible indeed. The component's properties are available in the component's template, but not in the template that instantiates the component.

If you need the component to make things available, it should yield them explicitly:

// templates/components/schedule/approvals.hbs
{{yield sectionTitle sectionDescription}}

And using the component:

// templates/approvals.hbs
{{#x-secure/schedule/approvals as |title description|}}

  {{#x-secure/layout/full sectionTitle=title sectionDescription=description}}
    ...
  {{/x-secure/layout/full}}

{{/x-secure/schedule/approvals}}

Notice the as |x y ...| notation to assign names to yielded values.

Anything may be yielded this way, including this (be careful with that though, that breaks encapsulation) and actions.

Upvotes: 1

Related Questions