Search code examples
ember.jsember-dataember-cli

How to send data from route to component?


I am beginner to ember.

I want to send data from route to component.

import Ember from 'ember';
var model = null;
export default Ember.Route.extend({
    model() {
        return true;
    }
});

i have defined this model in route now i want to use this model in component js file. i have just do console log but it gives undefined. my component js code is below

import Ember from 'ember';
export default Ember.Component.extend({
    didInsertElement() {
        console.log(model);
    }
});

So can anyone suggest what is the actual way to use data of route in component.


Solution

  • You just return the data you need to pass it to template,

    import Ember from 'ember';
    export default Ember.Route.extend({
        model() {
            //here return model data which requires to display template
            return true;
        }
    });
    

    Inside template you can access is using model, in this case you just sent true so your model will contains true.

    You need to pass this model to component so that you can access it from component. Inside template.hbs,

    {{my-component model=model }}
    

    You can access model property in component,

    import Ember from 'ember';
    export default Ember.Component.extend({
        didInsertElement() {
            console.log('Model ',this.get('model'));
        }
    });
    

    Welcome to Ember. I am strongly encouraging you to read ember guides and play with ember-twiddle