javascript - Angular : Detect click event inside a div with ngFor inside -


i'm working on application lot of dropdowns, able close dropdown whenever click happens outside of one.

i found solutions, none of them handle case of having ngfor in it, when log click event target in ngfor, element 1 doesn't have parent. can not detect 'find' or 'contains' neither.

does have solution detect if target part of dropdown ?

the directive

import { directive, elementref, eventemitter, input, oninit, output, simplechange } '@angular/core';  @directive({selector: '[clickoutside]'}) export class clickoutside implements oninit { @output() clickoutside:eventemitter<event> = new eventemitter<event>();  constructor(private _el:elementref) {     this.onclickbody = this.onclickbody.bind(this); }  ngoninit() {     document.body.addeventlistener('click', this.onclickbody); }  private onclickbody(e:event) {     if (!this.isclickinelement(e)) {         this.clickoutside.emit(e);     } }  private isclickinelement(e:any):boolean {     var current = e.target;     {         console.log(current);         if ( current === this._el.nativeelement ) {             return( true );         }         current = current.parentnode;     } while ( current );     return false; } } 

example of call directive

   <div (clickoutside)="onclickedoutside($event)">             <ul>                 <li *ngfor="let item of itemslist" (click)="selectitem(item)">                   <span class="item">                     {{item.name}}                   </span>                 </li>             </ul>         </div> 

when click on item.name, console.log(current); returns me 2 lines

<span>item</span>   <li>   <span>item</span> </li> 

@directive({selector: '[clickoutside]'}) export class clickoutside implements oninit {   @output() clickoutside:eventemitter<event> = new eventemitter<event>();    constructor(private _eref: elementref) { }    @hostlistener('window:click')   private onclickbody(e:event) {     if (!this.isclickinelement(e)) {         this.clickoutside.emit(e);     }   }    private isclickinelement(e:any):boolean {     return this._eref.nativeelement.contains(event.target);   } } 

see https://stackoverflow.com/a/35713421/217408


Comments

Popular posts from this blog

java - Static nested class instance -

c# - Bluetooth LE CanUpdate Characteristic property -

JavaScript - Replace variable from string in all occurrences -