Reputation: 8202
How to listen to click event on the component and call a method on the component?
Ex -
Component
import { Component } from '@angular/core';
@Component({
selector: 'my-component',
template: `
<div>Hello my name is {{name}}. </div>
`
})
export class MyComponent {
name = "Aj"
}
HTML -
<my-component></my-component> // user clicks here
Now how do I listen to click on the component itself?
Upvotes: 18
Views: 34358
Reputation: 15343
Update: Rahul Singh has the right answer
Use the host
property of the @Component
decorator:
@Component({
...,
host: { '(click)': 'onClick()'}
})
export class MyComponent {
private onClick() {
console.log('onClick');
}
}
Upvotes: 9
Reputation: 19622
Use HostListener
in your component. The answer given by Ploppy works, but Angular tells you to use HostListener
in your component instead like this
import { HostListener } from "@angular/core";
@Component({
[...]
})
export class MyComponent {
@HostListener("click") onClick(){
console.log("User Click using Host Listener")
}
}
Upvotes: 33
Reputation: 255
The same way as you monitor for a click anywhere, with the (click)="myFunction" syntax.
The details can be found here at the Angular docs. https://angular.io/docs/ts/latest/guide/template-syntax.html#!#event-binding
When you say "on the component itself", if you mean that you don't want the parent element listening for the click, then simply put the (click) handler in your component template instead of the parent's tag. In this scenario, the parent will be unaware of the captured click.
Upvotes: 0