Close the drop-down menu when opening the second page /document.click is blocked by clicking Angular 5

I am trying to create a directive for a drop-down list, while I work with a single one, it works like a charm. I can specify a drop down list using the following code:

@HostListener('document:click', ['$event'])
  onDocumentClick(event: any): void {
    console.log("document click");
    // close
}
@HostListener('click')
  onClick(): void {
    console.log('click on ');  
    // toggle  
  }

The problem arises when creating two drop-down menus. I would like to close the first drop-down menu when opening the second, however, when I click on the second drop-down list, only the "click" event fires, and "document.click" is not executed. I would expect both events to happen if I do not explicitly use preventDefault for a click, but apparently this happens automatically.

What should be the right approach in Angular 5 to close the first expansion when opening the second page?

+6
2

, - :

 @HostListener('document:click', ['$event'])
  onClick(event) {
    if(this.eRef.nativeElement.contains(event.target)) {
      // toggle logic
    } else {
      // close logic
    }
}

, , , , , , . ?

0

, ?

@Directive( {
    selector : '[clicked-outside]' ,
    host     : {
        '(document:click)' : 'onClick($event)',
        '(document:touch)' : 'onClick($event)',
        '(document:touchstart)' : 'onClick($event)'
    } 
} )
export class ClickedOutsideDirective {
    @Input( 'clicked-outside' ) callback : Function;

    constructor ( private _el : ElementRef ) {
    }

    private onClick ( event : any ) {
        if ( this.clickedOutside( event ) ) {
            if ( this.callback ) {
                this.callback();
            }
        }
    }

    private clickedOutside ( event : any ) {
        let clickedTarget = event.target;
        let host          = this._el.nativeElement;
        do {
            if ( clickedTarget === host ) {
                return false;
            }
            clickedTarget = clickedTarget.parentNode;
        } while ( clickedTarget );
        return true;
    }
}

:

@Component({
   selector:'your-dropdown',
   template:`
       <div class="your-dropdown-top-most-wrapper" [clicked-outside]="onClickOutSide"></div>

   `
})
export class YouDropdownComponent{


   public onClickOutSide = ()=>{


        this.closeMyDropdown()// this is your function that closes the dropdown
   }
}
0

All Articles