在Angular 4中,EventEmitter emit无法正常工作

11

以下是我的代码:

search.component.html

<button (click)="addMe()">Click</button>

search.component.ts

import { Component, Directive, OnInit, Input, Output, EventEmitter } from '@angular/core';

@Component({
   selector: 'search-component',
   templateUrl: './search.component.html'
})

export class SearchComponent {
   @Output() userUpdated = new EventEmitter();

   addMe() {
       this.userUpdated.emit('my data to emit');
   }
}

profile.component.html

<search-component (userUpdated)="handleUserUpdated($event)"></search-component>

profile.component.ts

handleUserUpdated(e) {
   console.log('e', e);
}

什么是错误? - Rahul Singh
模块长什么样? - Swoox
1
你确定 SearchComponent 已经实例化了吗?你是否将它添加到了 declarations:[] 中? - Günter Zöchbauer
1
new EventEmitter<any>(); - Swoox
你有更新吗?你找到原因了吗? - Saeed Neamati
显示剩余4条评论
1个回答

1
你需要声明一个类型。如果你想要它是字符串,使用@Output() userUpdated = new EventEmitter<string>();;如果它可以是任何类型,则使用@Output() userUpdated = new EventEmitter<any>();
另外,你需要更改控制台日志,尝试切换到console.log("e-" + e)

1
这正是我想建议的,不确定为什么你被踩了。 - SeanOlson
2
这是因为你显然不需要为EventEmitter声明类型,尽管如果你不这样做,智能感知会抱怨。 - mast3rd3mon
你的意思不是打字本身,而是使用赋值和类型正确初始化EventEmitter。否则,它将无法工作。 - seawave_23
@Nadine 这个最初是为 Angular 4 设计的,如果我没记错的话,由于文档不适用于 v7/8,所以事情可能已经发生了变化。 - mast3rd3mon
@Nadine,这正是这个答案所做的事情,或者至少在撰写时是这样的。 - mast3rd3mon
显示剩余3条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接