Angular 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 from search component');运行,没有为发射引发错误)但我从未进入NotifyClicked()上的父处理程序,

将变量更改为,

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

除非您的父组件不是直接侦听子组件(如您的文章中所述),而是侦听其父组件之一,否则您的代码应该可以工作。Angular不支持事件冒泡,所以如果您的父组件有下面的代码示例,它将不会得到消息:

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

我的步骤是正确的,我必须重新启动我的dev-env,无论谁到达这里-不要浪费时间阅读这个用例。

最新更新