gpt4 book ai didi

Angular 2 在指令中动态添加主机监听器

转载 作者:行者123 更新时间:2023-12-05 09:19:28 25 4
gpt4 key购买 nike

我有一个在点击时打开子菜单的指令,但我想通过仅在点击目标元素时激活文档点击来改进它。所以问题是改进这个指令或者如何动态添加主机监听器。

import { Directive, HostListener, Input, AfterContentInit, ElementRef, ViewContainerRef, ContentChild } from '@angular/core';

@Directive({
selector: '[appSubMenu]'
})

export class SubMenuDirective implements AfterContentInit {
private visible: boolean = false;
@ContentChild('subMenu') child: ElementRef;

constructor(private vcRef: ViewContainerRef) { }

ngAfterContentInit() {
this.child.nativeElement.style.display = 'none';
}

@HostListener('document:click', ['$event', '$event.target'])
show(event:MouseEvent, targetElem: HTMLElement): void {
if (this.vcRef.element.nativeElement === targetElem && !this.visible) {
this.child.nativeElement.style.display = 'block';
this.visible = true;
} else {
this.child.nativeElement.style.display = 'none';
this.visible = false;
}
}
}

最佳答案

您可以使用渲染器类来实现动态事件绑定(bind)。存在两个函数:

  • listen:监听来自元素的事件
  • listenGlobal:监听全局事件,例如文档、正文

所以在你的情况下它看起来像下面这样:

import { Directive, HostListener, Input, AfterContentInit, ElementRef, ViewContainerRef, ContentChild } from '@angular/core';

@Directive({
selector: '[appSubMenu]'
})

export class SubMenuDirective implements AfterContentInit {
private visible: boolean = false;
private unregister: Function;
@ContentChild('subMenu') child: ElementRef;

constructor(private vcRef: ViewContainerRef, private renderer: Renderer) { }

ngAfterContentInit() {
this.child.nativeElement.style.display = 'none';
}


@HostListener('click', ['$event'])
elementClicked(event: MouseEvent) {
this.visible = !this.visible;
if (this.visible) {
this.unregister = this.renderer.listenGlobal('document', 'click', () => {
this.child.nativeElement.style.display = 'none';
this.unregister();
});
} else {
this.child.nativeElement.style.display = 'block';
}
}
}

关于Angular 2 在指令中动态添加主机监听器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40687746/

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