angularjs - Capturing next click on document from @HostListener (dynamically creating a click listener) in Angular 4 -
i have directive toggles it's state when clicked. if state active, , user clicks anywhere else on page, state should deactivated.
i have tried achieve using new renderer2 listen function dynamically generate listener catch "next click" - issue here callback function executes listener created! - 1 click activates, , deactivates element. i'm looking understanding why happening , need address it.
directive:
import { directive, elementref, input, output, hostlistener, eventemitter, renderer2 } '@angular/core'; @directive({ selector: '[emclicktoclose]' }) export class clicktoclosedirective { @input('emclicktoclose') openctrl: boolean; @output() ctrlupdate: eventemitter<boolean> = new eventemitter(); @hostlistener('click', ['$event']) onclick(e: mouseevent) { this.openctrl = !this.openctrl; this.ctrlupdate.emit(this.openctrl); if (this.openctrl) { const removeregisteredlistener = this.renderer.listen('document', 'click', () => { console.log('the document clicked', this.openctrl); this.openctrl = false; this.ctrlupdate.emit(this.openctrl); removeregisteredlistener(); }); } } constructor(private el: elementref, private renderer: renderer2) { } }
events bubble child parent, , since add event listener while event still propagated, document being ultimate parent receive click event. need stop propagation of event using. e.stoppropagation();
in click handler.
Comments
Post a Comment