如何click事件绑定到整个组件(又名:主机)在角2
问题描述:
我有一个容器组件包含一些孩子,ChildComponent
ContainerComponent
,催生了与* ngFor如何click事件绑定到整个组件(又名:主机)在角2
ContainerComponent
模板:
<div class="child" *ngFor="let child of children">
<child [child]="child"></child>
</div>
ChildComponent
模板:
<h2>{{child.name}}</h2>
<h2>{{child.data}}</h2>
对于ChildComponent,我有一个样式表定义,我可以在其中访问整个组件使用:host
(https://angular.io/docs/ts/latest/guide/component-styles.html)NT身体
有了这个,我创建样式ChildComponent
:
:host
{
display: block;
width: 400px;
height: 300px;
}
现在我要绑定(点击)每个ChildComponent
(整个组件)的事件,并抓住它里面ChildComponent
类。要做到这一点,我必须设置(点击)=“方法”属性东西。
但是我不这样做:在谈论事件时,主持人般的东西。
我不想在ContainerComponent
中绑定。
一个可能的解决方案是将整个组件包装在div中并将事件绑定到此div,但是我正在寻找一种更优雅的方式。
答
选项1:
在组件元数据中指定单击主处理器
host: {
"(click)": "onClick($event)"
}
在组件实现单击处理
onClick(e) {
console.log(e)
}
选项2:
使用HostListener到为该组件添加侦听器。
import {Component, HostListener} from "@angular/core";
...
enter code here
...
@HostListener('click', ['$event'])
onClick(e) {
console.log(e);
}