gpt4 book ai didi

angular - 指令单击外 Angular 6

转载 作者:太空狗 更新时间:2023-10-29 17:12:47 26 4
gpt4 key购买 nike

我将我的 Angular 从 4 升级到 6,因此我的点击关闭政策出现问题,它停止在所有组件上工作。

我的指令:

import { Directive, Output, EventEmitter, ElementRef, HostListener } from '@angular/core';

@Directive({
selector: '[clickOutside]'
})
export class ClickOutsideDirective {

constructor(private _elementRef : ElementRef) { }

@Output()
public clickOutside = new EventEmitter();

@HostListener('document:click', ['$event.target'])
public onClick(targetElement) {
const clickedInside = this._elementRef.nativeElement.contains(targetElement);
if (!clickedInside) {
this.clickOutside.emit(null);
}
}
}

我的 component.html 使用了这个指令:

<div 
id="sidenav"
*ngIf="this.opened"
class="sidenav"
[ngClass]="getClasses()"
[ngStyle]="getStyles()"
clickOutside
(clickOutside)="closeOutsideSidenav()"
>
<header> {{ navTitle }} </header>
<i
*ngIf="this.showCloseButton"
class="iconic iconic-x-thin close-icon"
(click)="closeSidenav()"
></i>
<ng-content></ng-content>
</div>
<div
*ngIf="this.backdrop && this.opened"
class="sidenav-backdrop"
></div>

最佳答案

View :

<div #insideElement></div>

组件:

export class SomeClass {
@ViewChild("insideElement") insideElement;
@HostListener('document:click', ['$event.target'])

public onClick(targetElement) {
const clickedInside = this.insideElement.nativeElement.contains(targetElement);
if (!clickedInside) {
console.log('outside clicked');
}
}
}

关于angular - 指令单击外 Angular 6,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50531212/

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