Detect click outside Angular component











up vote
32
down vote

favorite
7












How can I detect clicks outside a component in Angular?










share|improve this question
























  • See also stackoverflow.com/questions/35527456/…
    – Günter Zöchbauer
    Oct 18 '16 at 11:39















up vote
32
down vote

favorite
7












How can I detect clicks outside a component in Angular?










share|improve this question
























  • See also stackoverflow.com/questions/35527456/…
    – Günter Zöchbauer
    Oct 18 '16 at 11:39













up vote
32
down vote

favorite
7









up vote
32
down vote

favorite
7






7





How can I detect clicks outside a component in Angular?










share|improve this question















How can I detect clicks outside a component in Angular?







html events angular typescript






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Dec 13 '17 at 22:50









Mark Amery

58.7k30234277




58.7k30234277










asked Oct 18 '16 at 11:27









AMagyar

1,0961814




1,0961814












  • See also stackoverflow.com/questions/35527456/…
    – Günter Zöchbauer
    Oct 18 '16 at 11:39


















  • See also stackoverflow.com/questions/35527456/…
    – Günter Zöchbauer
    Oct 18 '16 at 11:39
















See also stackoverflow.com/questions/35527456/…
– Günter Zöchbauer
Oct 18 '16 at 11:39




See also stackoverflow.com/questions/35527456/…
– Günter Zöchbauer
Oct 18 '16 at 11:39












3 Answers
3






active

oldest

votes

















up vote
68
down vote



accepted










import { Component, ElementRef, HostListener, Input } from '@angular/core';

@Component({
selector: 'selector',
template: `
<div>
{{text}}
</div>
`
})
export class AnotherComponent {
public text: String;

@HostListener('document:click', ['$event'])
clickout(event) {
if(this.eRef.nativeElement.contains(event.target)) {
this.text = "clicked inside";
} else {
this.text = "clicked outside";
}
}

constructor(private eRef: ElementRef) {
this.text = 'no clicks yet';
}
}


Plunker working example - click here






share|improve this answer



















  • 4




    This doesn't work when there is an element controlled by an ngIf inside the trigger element, since the ngIf removing the element from the DOM happens before the click event: plnkr.co/edit/spctsLxkFCxNqLtfzE5q?p=preview
    – J. Frankenstein
    Oct 9 '17 at 23:23










  • does it work on a component that created dynamiclly via : const factory = this.resolver.resolveComponentFactory(MyComponent); const elem = this.vcr.createComponent(factory);
    – Avi Moraly
    Feb 12 at 17:19


















up vote
11
down vote













An alternative to AMagyar's answer. This version works when you click on element that gets removed from the DOM with an ngIf.



http://plnkr.co/edit/4mrn4GjM95uvSbQtxrAS?p=preview






  private wasInside = false;

@HostListener('click')
clickInside() {
this.text = "clicked inside";
this.wasInside = true;
}

@HostListener('document:click')
clickout() {
if (!this.wasInside) {
this.text = "clicked outside";
}
this.wasInside = false;
}








share|improve this answer




























    up vote
    1
    down vote













    You can useclickOutside() method from https://www.npmjs.com/package/ng-click-outside package






    share|improve this answer





















      Your Answer






      StackExchange.ifUsing("editor", function () {
      StackExchange.using("externalEditor", function () {
      StackExchange.using("snippets", function () {
      StackExchange.snippets.init();
      });
      });
      }, "code-snippets");

      StackExchange.ready(function() {
      var channelOptions = {
      tags: "".split(" "),
      id: "1"
      };
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function() {
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled) {
      StackExchange.using("snippets", function() {
      createEditor();
      });
      }
      else {
      createEditor();
      }
      });

      function createEditor() {
      StackExchange.prepareEditor({
      heartbeatType: 'answer',
      convertImagesToLinks: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      imageUploader: {
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      },
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      });


      }
      });














      draft saved

      draft discarded


















      StackExchange.ready(
      function () {
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f40107008%2fdetect-click-outside-angular-component%23new-answer', 'question_page');
      }
      );

      Post as a guest















      Required, but never shown

























      3 Answers
      3






      active

      oldest

      votes








      3 Answers
      3






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes








      up vote
      68
      down vote



      accepted










      import { Component, ElementRef, HostListener, Input } from '@angular/core';

      @Component({
      selector: 'selector',
      template: `
      <div>
      {{text}}
      </div>
      `
      })
      export class AnotherComponent {
      public text: String;

      @HostListener('document:click', ['$event'])
      clickout(event) {
      if(this.eRef.nativeElement.contains(event.target)) {
      this.text = "clicked inside";
      } else {
      this.text = "clicked outside";
      }
      }

      constructor(private eRef: ElementRef) {
      this.text = 'no clicks yet';
      }
      }


      Plunker working example - click here






      share|improve this answer



















      • 4




        This doesn't work when there is an element controlled by an ngIf inside the trigger element, since the ngIf removing the element from the DOM happens before the click event: plnkr.co/edit/spctsLxkFCxNqLtfzE5q?p=preview
        – J. Frankenstein
        Oct 9 '17 at 23:23










      • does it work on a component that created dynamiclly via : const factory = this.resolver.resolveComponentFactory(MyComponent); const elem = this.vcr.createComponent(factory);
        – Avi Moraly
        Feb 12 at 17:19















      up vote
      68
      down vote



      accepted










      import { Component, ElementRef, HostListener, Input } from '@angular/core';

      @Component({
      selector: 'selector',
      template: `
      <div>
      {{text}}
      </div>
      `
      })
      export class AnotherComponent {
      public text: String;

      @HostListener('document:click', ['$event'])
      clickout(event) {
      if(this.eRef.nativeElement.contains(event.target)) {
      this.text = "clicked inside";
      } else {
      this.text = "clicked outside";
      }
      }

      constructor(private eRef: ElementRef) {
      this.text = 'no clicks yet';
      }
      }


      Plunker working example - click here






      share|improve this answer



















      • 4




        This doesn't work when there is an element controlled by an ngIf inside the trigger element, since the ngIf removing the element from the DOM happens before the click event: plnkr.co/edit/spctsLxkFCxNqLtfzE5q?p=preview
        – J. Frankenstein
        Oct 9 '17 at 23:23










      • does it work on a component that created dynamiclly via : const factory = this.resolver.resolveComponentFactory(MyComponent); const elem = this.vcr.createComponent(factory);
        – Avi Moraly
        Feb 12 at 17:19













      up vote
      68
      down vote



      accepted







      up vote
      68
      down vote



      accepted






      import { Component, ElementRef, HostListener, Input } from '@angular/core';

      @Component({
      selector: 'selector',
      template: `
      <div>
      {{text}}
      </div>
      `
      })
      export class AnotherComponent {
      public text: String;

      @HostListener('document:click', ['$event'])
      clickout(event) {
      if(this.eRef.nativeElement.contains(event.target)) {
      this.text = "clicked inside";
      } else {
      this.text = "clicked outside";
      }
      }

      constructor(private eRef: ElementRef) {
      this.text = 'no clicks yet';
      }
      }


      Plunker working example - click here






      share|improve this answer














      import { Component, ElementRef, HostListener, Input } from '@angular/core';

      @Component({
      selector: 'selector',
      template: `
      <div>
      {{text}}
      </div>
      `
      })
      export class AnotherComponent {
      public text: String;

      @HostListener('document:click', ['$event'])
      clickout(event) {
      if(this.eRef.nativeElement.contains(event.target)) {
      this.text = "clicked inside";
      } else {
      this.text = "clicked outside";
      }
      }

      constructor(private eRef: ElementRef) {
      this.text = 'no clicks yet';
      }
      }


      Plunker working example - click here







      share|improve this answer














      share|improve this answer



      share|improve this answer








      edited Dec 13 '17 at 22:59









      Mark Amery

      58.7k30234277




      58.7k30234277










      answered Oct 18 '16 at 11:27









      AMagyar

      1,0961814




      1,0961814








      • 4




        This doesn't work when there is an element controlled by an ngIf inside the trigger element, since the ngIf removing the element from the DOM happens before the click event: plnkr.co/edit/spctsLxkFCxNqLtfzE5q?p=preview
        – J. Frankenstein
        Oct 9 '17 at 23:23










      • does it work on a component that created dynamiclly via : const factory = this.resolver.resolveComponentFactory(MyComponent); const elem = this.vcr.createComponent(factory);
        – Avi Moraly
        Feb 12 at 17:19














      • 4




        This doesn't work when there is an element controlled by an ngIf inside the trigger element, since the ngIf removing the element from the DOM happens before the click event: plnkr.co/edit/spctsLxkFCxNqLtfzE5q?p=preview
        – J. Frankenstein
        Oct 9 '17 at 23:23










      • does it work on a component that created dynamiclly via : const factory = this.resolver.resolveComponentFactory(MyComponent); const elem = this.vcr.createComponent(factory);
        – Avi Moraly
        Feb 12 at 17:19








      4




      4




      This doesn't work when there is an element controlled by an ngIf inside the trigger element, since the ngIf removing the element from the DOM happens before the click event: plnkr.co/edit/spctsLxkFCxNqLtfzE5q?p=preview
      – J. Frankenstein
      Oct 9 '17 at 23:23




      This doesn't work when there is an element controlled by an ngIf inside the trigger element, since the ngIf removing the element from the DOM happens before the click event: plnkr.co/edit/spctsLxkFCxNqLtfzE5q?p=preview
      – J. Frankenstein
      Oct 9 '17 at 23:23












      does it work on a component that created dynamiclly via : const factory = this.resolver.resolveComponentFactory(MyComponent); const elem = this.vcr.createComponent(factory);
      – Avi Moraly
      Feb 12 at 17:19




      does it work on a component that created dynamiclly via : const factory = this.resolver.resolveComponentFactory(MyComponent); const elem = this.vcr.createComponent(factory);
      – Avi Moraly
      Feb 12 at 17:19












      up vote
      11
      down vote













      An alternative to AMagyar's answer. This version works when you click on element that gets removed from the DOM with an ngIf.



      http://plnkr.co/edit/4mrn4GjM95uvSbQtxrAS?p=preview






        private wasInside = false;

      @HostListener('click')
      clickInside() {
      this.text = "clicked inside";
      this.wasInside = true;
      }

      @HostListener('document:click')
      clickout() {
      if (!this.wasInside) {
      this.text = "clicked outside";
      }
      this.wasInside = false;
      }








      share|improve this answer

























        up vote
        11
        down vote













        An alternative to AMagyar's answer. This version works when you click on element that gets removed from the DOM with an ngIf.



        http://plnkr.co/edit/4mrn4GjM95uvSbQtxrAS?p=preview






          private wasInside = false;

        @HostListener('click')
        clickInside() {
        this.text = "clicked inside";
        this.wasInside = true;
        }

        @HostListener('document:click')
        clickout() {
        if (!this.wasInside) {
        this.text = "clicked outside";
        }
        this.wasInside = false;
        }








        share|improve this answer























          up vote
          11
          down vote










          up vote
          11
          down vote









          An alternative to AMagyar's answer. This version works when you click on element that gets removed from the DOM with an ngIf.



          http://plnkr.co/edit/4mrn4GjM95uvSbQtxrAS?p=preview






            private wasInside = false;

          @HostListener('click')
          clickInside() {
          this.text = "clicked inside";
          this.wasInside = true;
          }

          @HostListener('document:click')
          clickout() {
          if (!this.wasInside) {
          this.text = "clicked outside";
          }
          this.wasInside = false;
          }








          share|improve this answer












          An alternative to AMagyar's answer. This version works when you click on element that gets removed from the DOM with an ngIf.



          http://plnkr.co/edit/4mrn4GjM95uvSbQtxrAS?p=preview






            private wasInside = false;

          @HostListener('click')
          clickInside() {
          this.text = "clicked inside";
          this.wasInside = true;
          }

          @HostListener('document:click')
          clickout() {
          if (!this.wasInside) {
          this.text = "clicked outside";
          }
          this.wasInside = false;
          }








            private wasInside = false;

          @HostListener('click')
          clickInside() {
          this.text = "clicked inside";
          this.wasInside = true;
          }

          @HostListener('document:click')
          clickout() {
          if (!this.wasInside) {
          this.text = "clicked outside";
          }
          this.wasInside = false;
          }





            private wasInside = false;

          @HostListener('click')
          clickInside() {
          this.text = "clicked inside";
          this.wasInside = true;
          }

          @HostListener('document:click')
          clickout() {
          if (!this.wasInside) {
          this.text = "clicked outside";
          }
          this.wasInside = false;
          }






          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Oct 9 '17 at 23:55









          J. Frankenstein

          587724




          587724






















              up vote
              1
              down vote













              You can useclickOutside() method from https://www.npmjs.com/package/ng-click-outside package






              share|improve this answer

























                up vote
                1
                down vote













                You can useclickOutside() method from https://www.npmjs.com/package/ng-click-outside package






                share|improve this answer























                  up vote
                  1
                  down vote










                  up vote
                  1
                  down vote









                  You can useclickOutside() method from https://www.npmjs.com/package/ng-click-outside package






                  share|improve this answer












                  You can useclickOutside() method from https://www.npmjs.com/package/ng-click-outside package







                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Oct 25 at 18:31









                  James Bond

                  112




                  112






























                      draft saved

                      draft discarded




















































                      Thanks for contributing an answer to Stack Overflow!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid



                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.


                      To learn more, see our tips on writing great answers.





                      Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


                      Please pay close attention to the following guidance:


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid



                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.


                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function () {
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f40107008%2fdetect-click-outside-angular-component%23new-answer', 'question_page');
                      }
                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      How to send String Array data to Server using php in android

                      Title Spacing in Bjornstrup Chapter, Removing Chapter Number From Contents

                      Is anime1.com a legal site for watching anime?