iJade
iJade

Reputation: 23801

Accessing passed binding in template

I tried creating a component using Angular 2. It works fine but I'm not really sure how to pass a value as binding. Here is the code:

(function(app) {
  app.AppComponent =
    ng.core.Component({
      selector: 'my-app',
      templateUrl: './app/grid.htm',
      bindings:{
          info:'=info'
      }
    })
    .Class({
      constructor: function() {
          this.items = [
                { id: 1, name: 'Roy', age: 25 },
                { id: 2, name: 'James', age: 30 }
            ];
      }
    });
})(window.app || (window.app = {}));

From the view part I'm passing in the items in the constructor as :

<my-app info="items">Loading...</my-app>

But I'm not able to access it in the template templateUrl: './app/grid.htm',

Here is the template code:

<tr *ngFor='#item of info'>
                    <td>
                        <span>{{ item.name }}</span>
                    </td> 
                    <td>
                        <span>{{ item.age }}</span>
                    </td>
 </tr>

But it's not working. Can any one point out what may be wrong ??

Upvotes: 0

Views: 241

Answers (1)

Thierry Templier
Thierry Templier

Reputation: 202176

@Input() is currently not supported on the root component (AppComponent).

See also https://github.com/angular/angular/issues/1858

As a workaround you can use

.Class({
  constructor: [ ElementRef, function(ref) {
    ref.nativeElement.getAttribute('mydata');
  }]
});

In your HTML file:

<my-app mydata="Some sample data">
  loading...
</my-app>

(allows only String)

But in your case, you don't need to have an info attribute. Since your data are loaded within the component and set into one of its properties, you can use them directly within your ngFor:

<tr *ngFor='#item of items'>
  (...)
</tr>

Edit

You can pass the data through an input element from the parent component (<display [data]="items"></display>), as described below:

App.DisplayComponent = ng.core
    .Component({
      selector: 'display',
      inputs: [ 'data' ],
      template: '<div>' +
        '  <tr *ngFor="#item of data">' +
        '    <td>' +
        '      <span>{{ item.name }}</span>' +
        '    </td>' +
        '    <td>' +
        '      <span>{{ item.age }}</span> ' +
        '    </td>' +
        '  </tr>' +
        '</div>'
    })
    .Class({
        constructor: function() {}
    });

App.AppComponent = ng.core
    .Component({
      selector: 'my-app',
      template: '<display [data]="items"></display>',
      directives: [App.DisplayComponent]
    })
    .Class({
        constructor: function() {
          this.items = [
            { id: 1, name: 'Roy', age: 25 },
            { id: 2, name: 'James', age: 30 }
          ];
        }
    });

Here is a sample plunkr: https://plnkr.co/edit/Ki6e9KgsPaiHIxfhKH3E?p=preview.

Upvotes: 1

Related Questions