![](/img/trans.png)
[英]child component emit an custom event, but parent component's listener not triggered
[英]Angular 4 parent component event listener won't triggered by child emitted event
我正在尝试将一个孩子的输出传递给它的父母,不知道为什么它不起作用,
儿童:
装饰者:
@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('来自搜索组件的消息');运行,没有为发出的错误抛出错误),但是我从未进入父处理程序onNotifyClicked(),
将变量更改为
@Output()
notify = new EventEmitter<string>();
除非您的父母不是直接在子组件中(如您的帖子中)而是在其中一个父组件上侦听,否则您的代码应该可以正常工作。 Angular不支持事件冒泡,因此,如果您的父组件具有以下类似代码示例的内容,它将不会收到以下消息:
<div (notify)="onNotifyClicked($event)">
<child></child>
</div>
我的步骤是正确的,无论谁到达这里,我都必须重新启动我的开发环境-不要浪费时间阅读此用例。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.