事件发出错误

Event emit error

所以我有这个代码 -

@Component({
  tag: "app-home",
  styleUrl: "app-home.css"
})
export class AppHome {
  @Event()
  myEvent: EventEmitter;

  callEv() {
    this.myEvent.emit("hello");
  }

  render() {
    return (
      <div class="app-home">
        <button onClick={this.callEv}>Hello</button>
      </div>
    );
  }
}

单击按钮时,我在控制台中收到此错误 -

Uncaught TypeError: Cannot read property 'emit' of undefined
    at HTMLButtonElement.callEv

知道为什么吗?

callEv 方法中,您使用 this 关键字来调用事件发射器服务。但在模板内部,上下文不同,因此 this 不包含事件发射器服务,这会导致您的错误。

您需要做的是将当前上下文绑定到方法上。将此添加到您的 class:

constructor() {
    this.callEv = this.callEv.bind(this);
}