【问题标题】:How to bind click event to whole component (aka :host)?如何将点击事件绑定到整个组件(又名:host)?
【发布时间】:2017-03-30 01:06:31
【问题描述】:

我有一个容器组件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(整个组件)上绑定 (click) 事件并将其捕获到 ChildComponent 类中。为此,我必须在 something 上设置 (click)="method" 属性。

但是,在谈论事件时,我没有 :host 之类的东西。

我不想绑定ContainerComponent

一种可能的解决方案是将整个组件包装在 div 中并将事件绑定到此 div,但我正在寻找一种更优雅的方式。

【问题讨论】:

    标签: angular


    【解决方案1】:

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

    【讨论】:

    猜你喜欢
    • 2020-07-11
    • 2011-09-17
    • 2014-09-04
    • 1970-01-01
    • 2011-05-18
    • 2012-03-10
    • 1970-01-01
    • 1970-01-01
    • 2021-09-03
    相关资源
    最近更新 更多