简体   繁体   English

Angular指令拦截点击事件

[英]Angular directive to intercept click event

I want a directive to intercept mouse click event on a whole component.我想要一个指令来拦截整个组件上的鼠标单击事件。

I wrote an Angular directive to intercept a mouse click event.我写了一个 Angular 指令来拦截鼠标点击事件。

@Directive({
    selector: '[interceptClick]'
})
export class InterceptClickDirective {
    constructor() {}

    @HostListener('click', ['$event'])
    onClick($event: MouseEvent): void {
      console.log('mouse clicked');
    }
}

I want to use it in a component, so I wrote我想在组件中使用它,所以我写了

<my-component interceptClick></my-component>

but this isn't working.但这不起作用。

If I write something like如果我写类似的东西

<div>
    <button interceptClick>my button</button>
</div>

The directive is working if I click the button.如果我单击按钮,该指令将起作用。

How do I make the directive work for the whole component?如何使指令对整个组件起作用?

I'm using Angular 13.我正在使用 Angular 13。

You can either wrap an HTML element around the component or add an HTML element to the component itself, and then add the directive.您可以将 HTML 元素包裹在组件周围,或者将 HTML 元素添加到组件本身,然后添加指令。

<div interceptClick>
    <my-component></my-component>
</div>

or in the component itself或者在组件本身

<div interceptClick>
    'All HTML content of the component'
</div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM