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?
Events are handled in Angular using the following special syntax. Bind the target event name within parentheses on the left of an equal sign, and event handler method or statement on the right. Above, (click) binds the button click event and onShow() statement calls the onShow() method of a component.
Introduction to AngularJs onclickThe ng-click directive can be used with multiple HTML elements such as button, input, select, checkbox, etc. This provides the developer ability to define custom behavior whenever an element is clicked.
An element receives a click event when a pointing device button (such as a mouse's primary mouse button) is both pressed and released while the pointer is located inside the element.
To go on detection for click outside the component, @HostListener decorator is used in angular. It is a decorator that declares a DOM event to listen for and provides a link with a handler method to run whenever that event occurs.
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")
}
}
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');
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With