Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to bind click event to whole component (aka :host)?

Tags:

I have a container component ContainerComponent containing some children, ChildComponent, spawned with *ngFor.

ContainerComponent template:

<div class="child" *ngFor="let child of children">     <child [child]="child"></child> </div> 

ChildComponent template:

<h2>{{child.name}}</h2> <h2>{{child.data}}</h2> 

For ChildComponent, I have a stylesheet defined, in which I can access whole component body using :host as described here.

With this, I created style for ChildComponent:

:host {     display: block;      width: 400px;     height: 300px; } 

Now, I want to bind the (click) event on each ChildComponent (whole component) and catch it inside ChildComponent class. To do this, I have to set (click)="method" property on something.

However, I don't have :host-like thing when talking about events.

I don't want to bind in ContainerComponent.

One possible solution is to wrap whole component in a div and bind event to this div, however I'm looking for a more elegant way.

like image 408
peku33 Avatar asked Nov 16 '16 00:11

peku33


People also ask

How to bind an event in Angular?

To bind to an event you use the Angular event binding syntax. This syntax consists of a target event name within parentheses to the left of an equal sign, and a quoted template statement to the right. Create the following example; the target event name is click and the template statement is onSave() .

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.

What is HostListener in Angular?

HostListenerlinkDecorator that declares a DOM event to listen for, and provides a handler method to run when that event occurs.


1 Answers

Option 1:

In component metadata specify click handler in host

host: {    "(click)": "onClick($event)" } 

Implement the click handler in the component

onClick(e) {    console.log(e) } 

Option 2:

Use HostListener to add listeners for the component.

import {Component, HostListener} from "@angular/core";  ... enter code here ...  @HostListener('click', ['$event']) onClick(e) {    console.log(e); } 
like image 190
Siva Avatar answered Oct 20 '22 18:10

Siva