如何检测用户是否点击了该div?

时间:2017-10-05 12:22:17

标签: angular

我想要的是检查用户是否点击了特定div中的任何位置。如果不做某事。我试过这个:

handleClick(event){
        var clickedComponent = event.target;
        console.log(event.target,'adsadasdas');
        var inside = false;
        do {
            if (clickedComponent === this._eref.nativeElement) {
                inside = true;
            }
            clickedComponent = clickedComponent.parentNode;
        } while (clickedComponent);
        if(inside){
            console.log('inside');
        }else{
            console.log('outside');
        }
    }

问题在于我对某些元素有*ngIf所以event.target有时是假的。所以现在我添加了一个包装器,我想检查用户是否在该包装器内单击。

2 个答案:

答案 0 :(得分:1)

请查看此指令信用 - https://christianliebel.com/2016/05/angular-2-a-simple-click-outside-directive/

import {Directive, ElementRef, Output, EventEmitter, 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);
        }
    }
}

另请查看此plunker

<强>更新

import { Subscription } from 'rxjs/Subscription';

答案 1 :(得分:1)

为什么你只是在视图中使用以下内容?

<div *ngIf="cond" (click)="myEventHandler"></div>

并在控制器中

myEventHandler(){
//do something
}