You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular模态父子组件用Output通信时数据返回undefined问题

Angular模态子组件与父组件数据通信问题解决

你遇到的问题核心是父组件错误地在componentProps中传入了新的EventEmitter实例,导致子组件内部的pushData和父组件监听的不是同一个对象,所以emit的数据无法被父组件接收到。

解决方案

  1. 移除父组件componentProps中的pushData配置,子组件已经通过output<Barcode>()定义了输出属性,无需外部传入。
  2. 父组件打开模态框后,通过模态框实例获取子组件的pushData事件并订阅。

修改后的父组件代码

public async startScan(): Promise<void> {
  const modal = await this.dialogService.showModal({
    component: ScannerComponent,
    cssClass: 'barcode-scanning-modal',
    showBackdrop: false,
  });

  // 订阅子组件的pushData事件
  modal.instance.pushData.subscribe((barcode: Barcode) => {
    console.log('接收到条码数据:', barcode);
    // 在这里处理条码数据,比如更新父组件状态
    modal.dismiss(); // 可选:获取数据后关闭模态框
  });
}

子组件代码(保持不变,注意Angular版本差异)

// Angular 16+ 语法
pushData = output<Barcode>();

// Angular 15及以下版本使用@Output装饰器
// @Output() pushData = new EventEmitter<Barcode>();

private processDetectedBarcode(barcode: Barcode): void {
  this.playBeepSound();
  this.pushData.emit(barcode);
}

为什么之前的写法无效?

父组件在componentProps中传入pushData: new EventEmitter<Barcode>(),相当于给子组件的pushData属性重新赋值了一个新实例。而子组件内部emit数据时,用的是自己初始定义的那个output实例,和父组件传入的不是同一个对象,自然无法触发父组件的订阅回调。

内容的提问来源于stack exchange,提问作者Hardy Rakoto

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.13 15:54:58