如何在Angular中检测组件外部的点击事件?
如何在Angular中检测组件外部的点击事件?
import { Component, ElementRef, HostListener, Input } from '@angular/core';
@Component({
selector: 'selector',
template: `
<div>
{{text}}
</div>
`
})
export class AnotherComponent {
public text: String;
@HostListener('document:click', ['$event'])
clickout(event) {
if(this.eRef.nativeElement.contains(event.target)) {
this.text = "clicked inside";
} else {
this.text = "clicked outside";
}
}
constructor(private eRef: ElementRef) {
this.text = 'no clicks yet';
}
}
AMagyar的答案的另一种选择。这个版本适用于你点击从DOM中通过ngIf移除的元素。
http://plnkr.co/edit/4mrn4GjM95uvSbQtxrAS?p=preview
private wasInside = false;
@HostListener('click')
clickInside() {
this.text = "clicked inside";
this.wasInside = true;
}
@HostListener('document:click')
clickout() {
if (!this.wasInside) {
this.text = "clicked outside";
}
this.wasInside = false;
}
将@Hostlistener绑定到文档的点击事件上是昂贵的。如果过度使用它(例如,在构建自定义下拉组件时创建了多个实例并且使用频繁),它将会产生明显的性能影响。
我建议仅在您的主应用程序组件中添加@Hostlistener()到文档点击事件一次。该事件应将所点击的目标元素的值推送到存储在全局实用程序服务中的公共主题中。
@Component({
selector: 'app-root',
template: '<router-outlet></router-outlet>'
})
export class AppComponent {
constructor(private utilitiesService: UtilitiesService) {}
@HostListener('document:click', ['$event'])
documentClick(event: any): void {
this.utilitiesService.documentClickedTarget.next(event.target)
}
}
@Injectable({ providedIn: 'root' })
export class UtilitiesService {
documentClickedTarget: Subject<HTMLElement> = new Subject<HTMLElement>()
}
对于所点击的目标元素感兴趣的人应该订阅我们的公共实用程序服务主题,并在组件被销毁时取消订阅。
export class AnotherComponent implements OnInit {
@ViewChild('somePopup', { read: ElementRef, static: false }) somePopup: ElementRef
constructor(private utilitiesService: UtilitiesService) { }
ngOnInit() {
this.utilitiesService.documentClickedTarget
.subscribe(target => this.documentClickListener(target))
}
documentClickListener(target: any): void {
if (this.somePopup.nativeElement.contains(target))
// Clicked inside
else
// Clicked outside
}
@HostListener('click')
clickInside($event) {
this.text = "clicked inside";
$event.stopPropagation();
}
@HostListener('document:click')
clickOutside() {
this.text = "clicked outside";
}
stopPropagation
可能会影响组件外的逻辑:Google Analytics、另一个组件的关闭等。 - Vincente$event
返回未定义。 - ShadowebisFocusInsideComponent = false;
isComponentClicked = false;
@HostListener('click')
clickInside() {
this.isFocusInsideComponent = true;
this.isComponentClicked = true;
}
@HostListener('document:click')
clickout() {
if (!this.isFocusInsideComponent && this.isComponentClicked) {
// Do the heavy processing
this.isComponentClicked = false;
}
this.isFocusInsideComponent = false;
}
ginalx的答案在我看来应该设为默认值:这种方法可以进行很多优化。
问题
假设我们有一个项目列表,每个项目都需要包含一个需要切换的菜单。我们在按钮上包含一个切换,它会监听自己的click
事件(click)="toggle()"
,但我们也希望在用户点击菜单外部时切换菜单。如果项目列表增长,并且我们在每个菜单上附加一个@HostListener('document:click')
,则即使菜单关闭,每个加载在项目中的菜单也将开始在整个文档中监听单击事件。除了明显的性能问题之外,这是不必要的。
例如,您可以订阅每次通过单击切换弹出窗口并仅在那时开始监听“外部单击”。
isActive: boolean = false;
// to prevent memory leaks and improve efficiency, the menu
// gets loaded only when the toggle gets clicked
private _toggleMenuSubject$: BehaviorSubject<boolean>;
private _toggleMenu$: Observable<boolean>;
private _toggleMenuSub: Subscription;
private _clickSub: Subscription = null;
constructor(
...
private _utilitiesService: UtilitiesService,
private _elementRef: ElementRef,
){
...
this._toggleMenuSubject$ = new BehaviorSubject(false);
this._toggleMenu$ = this._toggleMenuSubject$.asObservable();
}
ngOnInit() {
this._toggleMenuSub = this._toggleMenu$.pipe(
tap(isActive => {
logger.debug('Label Menu is active', isActive)
this.isActive = isActive;
// subscribe to the click event only if the menu is Active
// otherwise unsubscribe and save memory
if(isActive === true){
this._clickSub = this._utilitiesService.documentClickedTarget
.subscribe(target => this._documentClickListener(target));
}else if(isActive === false && this._clickSub !== null){
this._clickSub.unsubscribe();
}
}),
// other observable logic
...
).subscribe();
}
toggle() {
this._toggleMenuSubject$.next(!this.isActive);
}
private _documentClickListener(targetElement: HTMLElement): void {
const clickedInside = this._elementRef.nativeElement.contains(targetElement);
if (!clickedInside) {
this._toggleMenuSubject$.next(false);
}
}
ngOnDestroy(){
this._toggleMenuSub.unsubscribe();
}
而在*.component.html
文件中:
<button (click)="toggle()">Toggle the menu</button>
tap
操作符中。相反,使用以下方式:skipWhile(() => !this.isActive),
switchMap(() => this._utilitiesService.documentClickedTarget),
filter((target) => !this._elementRef.nativeElement.contains(target)),
tap(() => this._toggleMenuSubject$.next(false))
这样可以更充分地利用 RxJs 并跳过一些订阅。 - GizrahclickOutside()
方法;它提供了一个指令 "用于处理元素外部的点击事件"。使用event.stopPropagation()的另一个可能的解决方案:
获取所有父级元素
var paths = event['path'] as Array<any>;
检查任何父组件是否是该组件
var inComponent = false;
paths.forEach(path => {
if (path.tagName != undefined) {
var tagName = path.tagName.toString().toLowerCase();
if (tagName == 'app-component')
inComponent = true;
}
});
if (inComponent) {
console.log('clicked inside');
}else{
console.log('clicked outside');
}
@HostListener('document:click', ['$event'])
clickout(event: PointerEvent) {
var paths = event['path'] as Array<any>;
var inComponent = false;
paths.forEach(path => {
if (path.tagName != undefined) {
var tagName = path.tagName.toString().toLowerCase();
if (tagName == 'app-component')
inComponent = true;
}
});
if (inComponent) {
console.log('clicked inside');
}else{
console.log('clicked outside');
}
}