None
None

Reputation: 9247

How to detect if user clicked on that div?

What i want is to check if user clicked anywhere in specific div. If not do something. I tried this:

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');
        }
    }

Problem with this is that i have *ngIf on some elements so event.target is sometime false. So now i added a wrapper around and i want to check if user clicked inside that wrapper.

Upvotes: 4

Views: 7805

Answers (2)

Daniel Tadros
Daniel Tadros

Reputation: 2357

why you just use in the view the following?

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

and in the controler

myEventHandler(){
//do something
}

Upvotes: 3

Rahul Singh
Rahul Singh

Reputation: 19622

Look at this Directive credits to - 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);
        }
    }
}

Also Look at this plunker

Update

import { Subscription } from 'rxjs/Subscription';

Upvotes: 4

Related Questions