gpt4 book ai didi

angular - 如何将点击事件绑定(bind)到整个组件(又名 :host)?

转载 作者:可可西里 更新时间:2023-11-01 02:53:28 26 4
gpt4 key购买 nike

我有一个容器组件 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com