ARM
ARM

Reputation: 1550

How to hand off model data to component in Ember 2.x

I have a route in ember which looks like

//fish.js
import Ember from 'ember';

export default Ember.Route.extend({
  model: function(params) {
    return Ember.RSVP.hash({
      fishPrices: this.store.query('fish-price', {filter: {type: params.type}}),
      type: params.type
    });
  }
});

My fish.hbs uses model.type to change text on the page. However, I need to hand model.fishPrices off to a component which plots the price of the fish as a function of time:

//fish-price-plot.js
import Ember from 'ember';
/* global Plotly */

export default Ember.Component.extend({
  didInsertElement() {
    console.log(this.get('model'));
    Plotly.plot( 'fish-price-plot', [{
      // ...
      //Need to access model.fishPrices here
  }
});

How do I access the model in this component? I see a lot of information that suggests that I should be able to do something like

var fishPrices = this.get('model.fishPrices');
//do something with fishPrices

but this always ends up undefined.

Upvotes: 1

Views: 92

Answers (1)

TameBadger
TameBadger

Reputation: 1590

One way is directly passing it to the component props like this:

// route template in which you want to use your component & model
{{fishprice-plot model=model}}

Have a look at the following twiddle that demo's the first use case.

The other is injecting a service into the component with the required data.

// components/fishprice-plot.js
export default Ember.Component.extend({
  fishData: Ember.inject.service()
});

Have a look at this twiddle that demonstrates passing data to a component more comprehensively, and also this part of the guides, as pointed out by @locks in comments.

You can also have a look at this SO link regarding passing properties to your component.

Upvotes: 2

Related Questions