How can I close a dropdown on click outside?

I would like to close my login menu dropdown when the user click anywhere outside of that dropdown, and I’d like to do that with Angular2 and with the Angular2 “approach”…

I have implemented a solution, but I really do not feel confident with it. I think there must be an easiest way to achieve the same result, so if you have any ideas … let’s discuss šŸ™‚ !

Here is my implementation:

The dropdown component:

This is the component for my dropdown:

  • Every time this component it set to visible, (For example: when the user click on a button to display it) it subscribe to a “global” rxjs subject userMenu stored within the SubjectsService.
  • And every time it is hidden, it unsubscribe to this subject.
  • Every click anywhere within the template of this component trigger the onClick() method, which just stop event bubbling to the top (and the application component)

Here is the code

export class UserMenuComponent {

    _isVisible: boolean = false;
    _subscriptions: Subscription<any> = null;

    constructor(public subjects: SubjectsService) {
    }

    onClick(event) {
        event.stopPropagation();
    }

    set isVisible(v) {
        if( v ){
            setTimeout( () => {
this._subscriptions =  this.subjects.userMenu.subscribe((e) => {
                       this.isVisible = false;
                       })
            }, 0);
        } else {
            this._subscriptions.unsubscribe();
        }
        this._isVisible = v;
    }

    get isVisible() {
        return this._isVisible;
    }
}

The application component:

On the other hand, there is the application component (which is a parent of the dropdown component):

  • This component catch every click event and emit on the same rxjs Subject (userMenu)

Here is the code:

export class AppComponent {

    constructor( public subjects: SubjectsService) {
        document.addEventListener('click', () => this.onClick());
    }
    onClick( ) {
        this.subjects.userMenu.next({});
    }
}

What bother me:

  1. I do not feel really comfortable with the idea of having a global Subject that act as the connector between those components.
  2. The setTimeout: This is needed because here is what happen otherwise if the user click on the button that show the dropdown:
    • The user click on the button (which is not a part of the dropdown component) to show the dropdown.
    • The dropdown is displayed and it immediately subscribe to the userMenu subject.
    • The click event bubble up to the app component and gets caught
    • The application component emit an event on the userMenu subject
    • The dropdown component catch this action on userMenu and hide the dropdown.
    • At the end the dropdown is never displayed.

This set timeout delay the subscription to the end of the current JavaScript code turn which solve the problem, but in a very in elegant way in my opinion.

If you know cleaner, better, smarter, faster or stronger solutions, please let me know šŸ™‚ !

1,899 thoughts on “How can I close a dropdown on click outside?”

  1. [url=https://ventolinhfaer.com/]buy asthma inhalers without an rx[/url] [url=https://kamagrapolo.com/]kamagra 100mg oral jelly for sale[/url] [url=https://vardenafilz.com/]levitra 20 mg dosage[/url] [url=https://essinreceta.com/]lowest price for viagra 100mg[/url] http://doctorkiva.com viagra pills buy

    Reply
  2. [url=https://levitrahims.com/]cost of levitra 20 mg[/url] [url=https://canadianvolk.com/]otc medications online[/url] [url=https://costpills.com/]viagra pills[/url] [url=https://doctorborat.com/]online viagra prescription[/url] http://sinrecetaes.com generico de viagra

    Reply
  3. [url=https://doviagra.com/]viagra online prescription uk[/url] [url=https://viagrabuycheap.com/]where can i buy viagra without a prescription[/url] [url=https://incrhealth.com/]purchase disulfiram[/url] [url=https://tadalafilmtab.com/]us tadalafil[/url] [url=https://phdtabs.com/]finasteride for hair loss[/url] [url=https://cialisextr.com/]buy cialis uk paypal[/url] [url=https://viagraconn.com/]pfizer viagra for sale[/url] [url=https://fasttadalafil.com/]cheap cialis generic[/url] [url=https://ivermectinop.com/]where to buy ivermectin cream[/url] [url=https://anycialis.com/]20mg cialis cost[/url]

    Reply
  4. How can I close a dropdown on click outside? – JavaScript Help ivermectina posologia [url=http://ivermectini.com]ivermectin for humans[/url] buy ivermectin online

    Reply
  5. Hey outstanding blog! Does running a blog such as this take
    a lot of work? I’ve very little understanding of computer programming however I was hoping to start my
    own blog soon. Anyway, if you have any suggestions or techniques
    for new blog owners please share. I understand this is off
    subject nevertheless I just wanted to ask. Appreciate it!

    Reply
  6. Nice blog here! Also your site loads up very fast! What host are you using?
    Can I get your affiliate link to your host? I wish my site loaded up as quickly as yours lol

    Reply
  7. Hello There. I found your blog using msn. This is an extremely well
    written article. I will make sure to bookmark it and come back to read more of
    your useful information. Thanks for the post. I’ll definitely
    comeback.

    Reply
  8. Simply desire to say your article is as surprising. The clarity on your post is just excellent and that
    i could think you’re a professional in this subject.

    Well with your permission allow me to snatch your RSS feed to stay
    up to date with coming near near post. Thank you 1,000,000 and please keep up the rewarding work.

    Reply
  9. Iā€™m not that much of a online reader to be honest but your sites really nice, keep it up!
    I’ll go ahead and bookmark your site to come back
    down the road. All the best

    Reply
  10. [url=https://viagrabl.online/]cheap viagra australia fast delivery[/url] [url=https://txpills.online/]malegra dxt without prescription[/url] [url=https://sildenafillight.online/]sildenafil soft gel[/url] [url=https://znpharmacy.online/]reputable canadian pharmacy[/url] [url=https://upspills.online/]modafinil online pharmacy usa[/url] [url=https://yasminrx.online/]yasmin green[/url] [url=https://wowviagra.online/]usa viagra over the counter[/url] [url=https://viagrasx.online/]buy viagra online discount[/url]

    Reply
  11. Do you mind if I quote a few of your posts as long as I provide credit and sources back
    to your blog? My website is in the exact same area of interest as yours and
    my visitors would genuinely benefit from some of the information you
    provide here. Please let me know if this okay with you.
    Regards! ps4 https://j.mp/3nkdKIi ps4 games

    Reply
  12. Pingback: viagra otc
  13. Pingback: viagra sale
  14. [url=http://sildenafilgpill.online/]sildenafil otc[/url] [url=http://twentymed.online/]ivermectin coronavirus[/url] [url=http://tadalafilxs.online/]tadalafil india online[/url] [url=http://wopills.online/]medication zovirax cream[/url] [url=http://oprpharmacy.online/]online pharmacy non prescription drugs[/url] [url=http://ordcialis.online/]cialis in canada cost[/url] [url=http://viagraextralowcost.online/]canadian generic viagra 100mg[/url]

    Reply
  15. Pingback: viagra alternative
  16. [url=https://onlinemediorder.online/]tadacip 10 mg price[/url] [url=https://viagrasildenafilcialistadalafil.online/]can you buy viagra over the counter in europe[/url] [url=https://healthytb.online/]motilium purchase online[/url] [url=https://viagradpn.online/]buy generic viagra canadian pharmacy[/url] [url=https://sildenafilbo.online/]sildenafil online australia[/url] [url=https://oprpharmacy.online/]best canadian online pharmacy[/url] [url=https://ivermectinxr.online/]generic ivermectin[/url]

    Reply
  17. Pingback: free cialis
  18. Pingback: viagra generic
  19. [url=https://cialisgoal.online/]generic viagra cialis[/url] [url=https://viagragif.online/]buy viagra usa online[/url] [url=https://viagrazzt.online/]how to order viagra[/url] [url=https://blinkpills.online/]buy colchicine india[/url]

    Reply
  20. Pingback: order viagra us
  21. Pingback: cialis logo
  22. Pingback: cheap viagra
  23. Pingback: cialis generic
  24. Pingback: viagra for sale us
  25. Pingback: cheap viagra 25