2016-03-04 45 views
0

我尝试使用AngularJS 2创建组件。它工作正常,但我不确定如何将值作为绑定传递。 下面是代码:AngularJS 2访问模板中传递的绑定

(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 = {})); 

从我传递中的项目在构造函数中的视图部分:

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

但我不能够访问它在模板templateUrl: './app/grid.htm',

这里是模板代码:

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

但它不是WO rking。任何一个可以指出什么可能是错误的?

回答

1

@Input()当前不支持根组件(AppComponent)。

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

见作为一种变通方法,您可以使用

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

在HTML文件中:

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

(只允许字符串)

但在你的情况,您不需要具有info属性。由于你的数据在组件中加载并放置到它的一个属性,你可以直接在你的ngFor使用它们:

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

编辑

您可以通过从输入元素传递数据如下所述父组件(<display [data]="items"></display>):

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 } 
      ]; 
     } 
    }); 

下面是一个示例plunkr:https://plnkr.co/edit/Ki6e9KgsPaiHIxfhKH3E?p=preview

+0

我可以知道'ref.nativeElement.getAttribute('mydata')'是否会理解他需要从'this.items'中获取'mydata',而不是从'attribute'中获取? –

+0

如何将使用属性将外部组件加载到组件的方式传递给组件? – iJade