2016-03-15 96 views
0

我是Angular 2中的新成員。我只是在角2中創建了一個基本組件。組件正在工作,但是當我在HTML中多次調用該組件時,它僅適用於第一次調用。如何在Angular 2中多次調用組件

下面是app.component.ts

import {Component} from 'angular2/core'; 
import {bootstrap} from 'angular2/platform/browser' 


@Component({ 
    selector: 'click-me', 
    template: `<input #box (keyup.enter)="values=box.value" 
      (blur)="onKey(box.value)" />`    
}) 

export class AppComponent { 

    clickMessage = ''; 
    onKey(value: string) { 

    } 

    onClickMe() {  
     this.clickMessage = 'You are my hero!'; 
    } 

bootstrap(AppComponent); 

當我在我的主要的index.html多次使用'<click-me></click-me>',它適用於第一個。

下面是index.html的

<html> 
<script> 
      System.config({ 
      packages: {   
       app: { 
       format: 'register', 
       defaultExtension: 'js' 
       } 
      } 
      }); 
      System.import('app/app.component') 
       .then(null, console.error.bind(console)); 
     </script> 
     </head> 
     <!-- 3. Display the application --> 
     <body> 

<click-me></click-me> 
<click-me></click-me> 
     </body> 
    </html> 

回答

3

發生這種情況的原因是因爲您試圖引導具有多個實例的根元素。在角2角,從1的到來,認爲bootstrap方法作爲ng-app相當於角1

爲了解決這個問題,只需創建一個新的組件,並將其導入到你的根AppComponent。這樣你就可以多次使用它,並且仍然可以將單個實例傳遞給你的方法bootstrap

這將是這個樣子:

import {bootstrap} from 'angular2/platform/browser' 
import {Component} from 'angular2/core'; 
import {DuplicateComponent} from 'app/duplicate.component.ts'; 

@Component({ 
    selector: 'my-app', 
    template: "<click-me></click-me><click-me></click-me>", 
    directives: [DuplicateComponent] 
}) 
export class AppComponent { } 

bootstrap(AppComponent); 

,然後將組件你想複製將包括當前的邏輯

import {Component} from 'angular2/core'; 

@Component({ 
    selector: 'click-me', 
    template: `<input #box (keyup.enter)="clickMessage=box.value" 
      (blur)="onKey(box.value)" /> 
      <button (click)="onClickMe()">Click</button>` 
}) 

export class DuplicateComponent { 
    clickMessage = ''; 
    onKey(value: string) { } 

    onClickMe() { 
     this.clickMessage = 'You are my hero!'; 
    } 
} 

它仍然出現在您的邏輯是有點過,但我認爲你正在尋找沿着這些方向的東西:

http://plnkr.co/edit/jcl7kZ4MzRBtL5WykoJj?p=preview

0

有老年beta版本的bug。嘗試更新到最新的angular2版本。

+0

我如何更新到lattest版本。它現在在測試版嗎? – sarath

+0

更新了npm更新 – muetzerich

+0

。但仍然有問題。 :-( – sarath

相關問題