2016-03-24 96 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

查看食譜,[家長監聽兒童活動](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