作者热门文章
- android - RelativeLayout 背景可绘制重叠内容
- android - 如何链接 cpufeatures lib 以获取 native android 库?
- java - OnItemClickListener 不起作用,但 OnLongItemClickListener 在自定义 ListView 中起作用
- java - Android 文件转字符串
我有一个容器组件 ContainerComponent
,其中包含一些子组件 ChildComponent
,使用 *ngFor
生成。
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
访问整个组件主体,如 here 所述.
有了这个,我为 ChildComponent
创建了样式:
:host
{
display: block;
width: 400px;
height: 300px;
}
现在,我想在每个 ChildComponent
(整个组件)上绑定(bind) (click)
事件,并在 ChildComponent
类中捕获它。为此,我必须在 something 上设置 (click)="method"
属性。
但是,在谈论事件时,我没有类似 :host
的东西。
我不想在 ContainerComponent
中绑定(bind)。
一个可能的解决方案是将整个组件包装在 div
中并将事件绑定(bind)到此 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);
}
关于angular - 如何将点击事件绑定(bind)到整个组件(又名 :host)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40621879/
我是一名优秀的程序员,十分优秀!