2016-03-04 48 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