Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Listen to click event on Angular component

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?

like image 429
Ajey Avatar asked May 13 '17 14:05

Ajey


People also ask

How does Angular handle click event?

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.

Can we use Onclick in Angular?

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.

Which components can detect click as an event?

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.

How do I detect a click outside an element in Angular?

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.


2 Answers

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")
  }

}
like image 80
Rahul Singh Avatar answered Oct 09 '22 21:10

Rahul Singh


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');
  }
}
like image 28
Ploppy Avatar answered Oct 09 '22 22:10

Ploppy