簡體   English   中英

Angular 4父組件事件監聽器不會被子事件觸發

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM