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

Angular使用$event接收字符串数组遇类型不匹配错误,求解决方案

解决Angular中@Output传递字符串数组的类型错误问题

问题现象

使用@Output和EventEmitter从子组件向父组件传递字符串数组时,触发类型错误:

Argument of type 'Event' is not assignable to parameter of type 'string[]'.
  Type 'Event' is missing the following properties from type 'string[]': length, pop, push, concat, and 29 more.ngtsc(2345)

错误原因分析

  1. 模板事件绑定错误:父组件模板将onNewResult事件绑定到了<calculator-body>组件,但实际发射事件的是<app-calculator-buttons>子组件;同时子组件的@Output属性名为onNewresult(小写r),与模板中绑定的onNewResult(大写R)大小写不匹配,导致Angular无法识别自定义事件,转而触发默认DOM Event事件,$event因此为Event类型,与父组件方法的string[]参数类型冲突。

  2. emit参数类型错误:子组件emitResult方法使用对象扩展运算符{...this.screenValues}将数组转为对象,传递的参数类型为Object而非string[],即使绑定正确也会触发类型不匹配错误。

修复步骤

1. 修正模板事件绑定

将事件绑定移至正确的子组件,并匹配子组件的@Output属性名:

<div class="container bg-secondary rounded  my-2 p-2" id="contenedor">
  <calculator-body></calculator-body>
  <app-calculator-buttons (onNewresult)="onNewResult($event)"></app-calculator-buttons>
</div>

2. 修正emit的参数类型

使用数组扩展运算符创建数组副本,确保传递的是string[]类型:

emitResult():void{
  this.onNewresult.emit([...this.screenValues])
} 

验证修复

完成上述修改后,子组件发射的string[]类型数据会被父组件正确接收,类型错误消失,父组件的onNewResult方法可正常打印传递的数组。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 01:08:34