Angular中@Output与ngModel配合报错:Event无法赋值给Character类型
Angular @Output 数据传递错误排查与修复
问题说明
正在学习Angular的@Output装饰器,用于实现子组件向父组件传递数据。当前通过ngModel绑定表单数据,ngSubmit触发方法发射Character类型数据,但父组件中$event出现类型错误:Argument of type 'Event' is not assignable to parameter of type 'Character'。将参数改为any后数据仍无法传递,需要保留ngModel并解决该问题。
错误提示
Argument of type 'Event' is not assignable to parameter of type 'Character'.
Type 'Event' is missing the following properties from type 'Character': nombre, poder.
相关代码片段
1. Character 接口
export interface Character { nombre: string, poder: number }
2. 子组件
TypeScript 代码
public personaje: Character = { nombre: '', poder: 0 } @Output('') public onNuevoPersonaje: EventEmitter<Character> = new EventEmitter<Character>(); agregarPersonaje() { console.log(this.personaje) if (this.personaje.nombre.length === 0 || this.personaje.poder < 0 ) {return;} console.log(this.personaje) this.onNuevoPersonaje.emit(this.personaje); }
HTML 代码
<form class='row' (ngSubmit)=agregarPersonaje()> <input type="text" [(ngModel)]='personaje.nombre' name='nombre' class='form-control mb-2' placeholder='Nombre personaje'> <input type="number" [(ngModel)]='personaje.poder' name='poder' class='form-control mb-2' placeholder='Ingrese poder'> <button type="submit" class='btn btn-primary'> Agregar </button> </form>
3. 父组件
TypeScript 代码
public onNuevoPersonaje(personaje: Character): void { console.log('Information received') console.log(personaje); }
HTML 代码
<div class="col"> <app-formulario (onNuevoPersonaje)="onNuevoPersonaje($event)"></app-formulario> </div>
解决方案
问题根源在子组件的@Output装饰器配置:
@Output('') // 空字符串别名属于错误配置,会导致Angular无法正确识别输出属性 public onNuevoPersonaje: EventEmitter<Character> = new EventEmitter<Character>();
修复步骤:
- 移除
@Output的空字符串参数,改为:
@Output() public onNuevoPersonaje: EventEmitter<Character> = new EventEmitter<Character>();
若需要指定别名,需保证别名与父组件绑定的事件名一致(例如@Output('nuevoPersonaje'),父组件就要写(nuevoPersonaje)="onNuevoPersonaje($event)")。
- 可选优化:发射数据时创建对象副本,避免后续子组件修改
personaje影响父组件数据:
this.onNuevoPersonaje.emit({...this.personaje});
- 验证
FormsModule导入:确保所在模块已导入FormsModule,否则ngModel无法正常工作:
import { FormsModule } from '@angular/forms'; @NgModule({ imports: [ // ...其他导入项 FormsModule ] }) export class YourModule { }
修复后,父组件的$event会正确接收Character类型数据,无需改为any,数据可正常传递。
内容的提问来源于stack exchange,提问作者Joaquin Ibañez Lopez
相关产品推荐
相关产品推荐

