24
votes

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.

1

1 Answers

52
votes

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