2016-03-24 8 views
1

出力値をアクセスできません:持つEventEmitter:これは私の親コンポーネントである

import {Component, Input} from 'angular2/core'; 
    import {ChildComponent} from '../../components/parent-child-and-child-parent-communication/child'; 

    @Component({ 
     selector: 'parent-component', 
     template: `<li *ngFor="#position of employees"> 
          {{position.name}}</li> 
          <child-component name="Accenture"></child-component> 
          Clicked data {{clicked}}`, 
     directives:[ChildComponent] 
    }) 

    export class ParentComponent{ 
     employees; 
     @Input() clicked; 
     constructor(){ 
      this.employees = [{ 
       id: 1, 
       name: "software developer" 
      }, 
      { 
       id: 2, 
       name: "Team Leader" 
      }, 
      { 
       id: 3, 
       name: "Project " 
      } 
      ] 
     } 
    } 

は、これは私の子コンポーネントである:

import {Component, Input, Output, EventEmitter} from 'angular2/core'; 

@Component({ 
    selector: 'child-component', 
    template: `office name: {{name}}. <br> chennai office list<br> <li *ngFor="#office of offices" (click)="selectOffice(office)"> 
         {{office.name}}</li>` 
}) 

export class ChildComponent{ 
    selectedOffice; 
    @Input() name; 
    @Output() clicked = new EventEmitter() 
    offices; 
    officename; 
    constructor(){ 
     this.offices = [ 
      { 
       id: 1, 
       name: "HCL Technology" 
      }, 
      { 
       id: 2, 
       name: "Accenture" 
      }, 
      { 
       id: 3, 
       name: "TCS" 
      } 
     ] 
    } 

    selectOffice(data) { 
     console.log(data) 
     this.officename = data; 
     this.clicked.emit(this.officename) 
    } 
} 

は私が親コンポーネントにクリックされたオフィスの名を送信し、それを表示したい この問題を解決するには?それ以外の場合は、クリックイベントトリガーの間に、あるコンポーネントから他のコンポーネントにデータを送信する方法を説明してください。

+0

Cookbookを参照してください、[親は子イベントを待ちます](https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#child-to-parent) –

答えて

1

あなたはclickedイベントは、子コンポーネント内で発生したときにメソッドを実行するためにこれを試みることができる:

@Component({ 
    selector: 'parent-component', 
    template: ` 
    <li *ngFor="#position of employees"> 
     {{position.name}} 
    </li> 
    <child-component (clicked)="displayClickedData($event)" 
        name="Accenture"></child-component> 
    Clicked data {{clicked}} 
    `, 
    directives:[ChildComponent] 
}) 
export class ParentComponent { 
    displayClickedData(data) { 
    this.clicked = data; 
    } 
} 

$event値は、イベントをトリガーしたときに使用される値に対応しています。あなたの場合:this.officename

clickedプロパティは@Inputである必要はありません。

関連する問題