Reputation: 4357
so I have this code -
@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>
);
}
}
When the button is clicked, I get this error in the console -
Uncaught TypeError: Cannot read property 'emit' of undefined at HTMLButtonElement.callEv
Any idea why?
Upvotes: 0
Views: 595
Reputation: 17613
Inside the callEv
method, you use the this
keyword to call the event emitter service. But inside the template, the context is different and therefore this
does not contain the event emitter service, which causes your error.
What you need to do is to bind the current context to the method. Add this to your class:
constructor() {
this.callEv = this.callEv.bind(this);
}
Upvotes: 4