如果使用* ngIf删除了子组件,则会触发Angular自定义Clickaway侦听器 [英] Angular custom clickaway listener is triggered if a child component is removed using *ngIf
问题描述
我有一个clickaway侦听器,它是使用App.component.ts
I have a clickaway listener as a directive that uses @HostListener
put on App.component.ts
@Component({
selector: "app-root",
templateUrl: "./app.component.html",
styleUrls: ["./app.component.css"],
})
export class AppComponent {
constructor(private clickaway: ClickawayService) {}
@HostListener("document:click", ["$event"]) documentClick(event: any): void {
this.clickaway.target.next(event.target);
}
}
@Directive({
selector: "[clickaway]",
})
export class ClickawayDirective implements OnInit, OnDestroy {
@Input() clickaway = null;
private subscription: Subscription = null;
constructor(
private clickawayService: ClickawayService,
private eleRef: ElementRef
) {}
ngOnInit() {
this.subscription = this.clickawayService.target.subscribe((target) => {
if (!this.eleRef.nativeElement.contains(target)) {
this.clickaway();
}
});
}
ngOnDestroy() {
this.subscription.unsubscribe();
}
}
ClickAway
服务仅提供了一个主题,可以收听AppComponent
上的document:click
.
The ClickAway
service just provides a subject to listen to document:click
on the AppComponent
.
我在具有由* ngIf控制的子元素的div上使用此指令,例如:
I am using this directive on a div that has child controlled by *ngIf, something like:
<div [clickaway]="doSomething">
<span *ngIf="isVisible">
<button (click)="closeSpan()">close</button> //closeSpan() sets isVisible to false.
</span>
</div>
问题是,每当我单击关闭时,它也会触发clickaway的doSomething函数.
The problem is whenever I click on close, it also triggers the clickaway's doSomething function.
我了解* ngIf从dom中删除了跨度,因此当指令运行时!this.eleRef.nativeElement.contains(target)
的计算结果为false,因为element不存在.
I understand that *ngIf removes the span from dom thus when the directive runs !this.eleRef.nativeElement.contains(target)
evaluates to false, since element is not there.
到目前为止,我尝试过的是:
What I have tried so far is:
closeSpan() {
setTimeout(() => this.isVisible = false, 100);
}
,并使用position: absolute
和很高的偏移量将跨度移出视线,并删除*ngIf
.
and moving the span out of view using position: absolute
and very high offsets and removing *ngIf
.
这些解决方案有效,但是我正在寻找一种更优雅的方法,最好是指令本身来处理这种情况.
These solutions work, but I am seeking a more elegant way, preferably the directive itself handling such cases.
谢谢
推荐答案
我对点击一下鼠标不熟悉,但是这样可以吗?
I'm not familiar with click away, but would something like this work?
<div [clickaway]="doSomething()">
<button *ngIf="isVisible" (click)="isVisible=false">close</button>
</div>
doSomething() {
if(this.isVisible) {
}
}
这篇关于如果使用* ngIf删除了子组件,则会触发Angular自定义Clickaway侦听器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!