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.
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() .
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.
HostListenerlinkDecorator that declares a DOM event to listen for, and provides a handler method to run when that event occurs.
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); }
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