2017-10-10 56 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的包膜,谁得到在这里 - 不要浪费你的时间阅读这个用例。