Angular中点击函数触发但@Output未发射事件问题排查
问题:Angular模态框关闭按钮的EventEmitter无响应
我正在给模态框设置“X”关闭按钮,目前能看到子组件点击函数内的控制台日志,但EventEmitter触发后父组件无响应。
父组件代码
parent.component.ts
import { Component, OnInit } from '@angular/core'; @Component({ selector: 'parent', templateUrl: './parent.component.html', styleUrls: ['./parent.component.scss'] }) export class ParentComponent implements OnInit { public configOpen = false; constructor() { } ngOnInit(): void { } doClose(event: any) { console.log(event); } }
parent.component.html
<div> ...page body... <div> <child (closeModal)="doClose($event)"></child>
子组件代码
child.component.ts
import { Component, EventEmitter, Input, OnInit, Output } from '@angular/core'; @Component({ selector: 'child', templateUrl: './child.component.html', styleUrls: ['./child.component.scss'] }) export class ChildComponent implements OnInit { @Output() closeModal = new EventEmitter<string>(); constructor() { } ngOnInit(): void { } doClose() { this.closeModal.emit("nice"); console.log("here"); } }
child.component.html
<div class="header-row"> <h6 class="title">Title</h6> <mat-icon class="collapse-toggle" (click)="doClose()">close</mat-icon> </div>
点击关闭按钮后,子组件doClose方法里的console.log("here")能正常输出,但父组件doClose方法里的日志完全看不到。我基本是按照Angular文档实现的,翻了Stack Overflow上相关问题也没解决,求排查思路。
补充:重启NPM时收到如下警告:
.../node_modules/@observablehq/plot/src/transforms/dodge.js depends on
'interval-tree-1d'. CommonJS or AMD dependencies can cause
optimization bailouts. For more info see:
https://angular.io/guide/build#configuring-commonjs-dependencies
排查思路
- 确认父组件模板中的
<child>标签就是当前触发事件的子组件实例:如果模态框是通过动态组件加载(比如ComponentFactoryResolver)创建的,模板里绑定的(closeModal)不会生效,需要在动态创建时手动订阅closeModal事件。 - 检查
@Output名称的大小写:Angular事件绑定是大小写敏感的,确保子组件的closeModal和父组件绑定的(closeModal)完全一致,没有拼写错误。 - 检查子组件的声明:确认子组件已经在父组件所在模块的
declarations数组中,或者通过其他模块exports后被正确导入。 - 验证EventEmitter的订阅情况:在子组件
doClose方法中加入console.log(this.closeModal.observers.length),如果输出为0,说明父组件没有正确绑定事件,需要排查组件实例的关联关系。 - 忽略NPM警告:这个警告是CommonJS依赖导致的优化提示,和EventEmitter无响应的问题无关,不需要处理。
内容的提问来源于stack exchange,提问作者PR06GR4MM3R
相关产品推荐
相关产品推荐

