Passing properties to a component

Components by default are isolated from their surroundings. Any data that the component needs must be passed in. In this recipe, we'll create a student list. However, we will pass data to the component to be rendered.

How to do it...

  1. In a new application, generate a new component and the application route:
    $ ember g route application
    $ ember g component student-list
    

    This will generate the application.js file in the routes folder and the files necessary from the student-list component.

  2. Edit the application.js file in the app/routes folder:
    // app/routes/application.js
    import Ember from 'ember';
    
    export default Ember.Route.extend({
        model() {
          return ['Jim','Jeff','Jill']
        }
    });

    This model will return a simple array.

  3. Update the student-list template in the app/templates/components folder:
    // app/templates/components/student-info.hbs
    
    {{#each compModel as |student|}}
        {{student}}<br>
    {{/each}}

    This will take the compModel property and iterate over it using the each helper.

  4. Edit the application.hbs file in the app/templates folder. Add the new student-info component:
    // app/templates/application.hbs
    {{student-list compModel=model}}
    
    {{outlet}}

    The student-list template has the compModel property. This property passes in the model that is the application model that we set up earlier in the route. Keep in mind that compModel is accessed from the inside of the component. The model is accessed outside the component. The component does not have any access to the model unless it's passed to it.

  5. Run ember server and you should see a list of elements in the model:
    How to do it...

How it works...

Components are isolated sets of code that do not have access to the outside world. In other words, components must have any data that it needs passed to it. You can set this up by adding properties after the name of the component in the Handlebars expression.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset