2017-10-10 55 views
0

我試圖從孩子的輸出傳遞到其父,引發 不知道爲什麼它只是將無法正常工作,角4父組件事件偵聽器不會被孩子發出的事件

兒童:

裝飾:

@Component({ 
    selector: 'child', 
    templateUrl: './child.component.html', 
    styleUrls: ['./child.component.css'] 
}) 

@Output() notify: EventEmitter<string> = new EventEmitter<string>(); 
onClick(){ 
    this.notify.emit('msg from child component'); 
} 

進口:

import { Component, OnInit, EventEmitter, Output } from '@angular/core'; 

模板:

<button (click)="onClick()"> search </button> 

父級:

onNotifyClicked(message: string): void { 
    this.showMsg = message; 
} 

模板:

<child (notify)="onNotifyClicked($event)"> </child> 

我到其中通知被髮出的狀態(this.notify.emit( 'MSG從搜索組件') ; 運行,沒有錯誤被拋出的發射) ,但我從來沒有在父處理器onNotifyClicked(),

+0

你怎麼知道的?你有沒有在父處理程序中放置一個console.log? – echonax

+0

@echonax我最初使用了斷點,並沒有進入處理程序,在您的評論後我添加了一個console.log,也沒有任何東西 – lironn

+0

您可以包括您的導入嗎?你在哪裏輸入'@輸出'? – echonax

回答

0

變化的變量,

@Output() 
notify = new EventEmitter<string>(); 
+0

感謝您的幫助,只是測試它,仍然不會進入onNotifyClicked(),我使用角4.2.4和typescript 2.3.3,任何想法? – lironn

+0

@lironn創建一個plunker – Sajeetharan

+0

有人爲我做了 - > https://stackblitz.com/edit/angular-a17ptm?file=app%2Fapp.component.ts – lironn

0

您的代碼應該工作,除非你的父母是聽不在子組件中直接(如在你的帖子中),但在其父母之一。角不支持事件冒泡,所以如果你的父母組件有類似下面的代碼示例,它不會得到消息:

<div (notify)="onNotifyClicked($event)"> 
    <child></child> 
</div> 
0

我的步驟是正確的,我不得不重新啓動我的dev的包膜,誰得到在這裏 - 不要浪費你的時間閱讀這個用例。