Angular 2 Dart: How to detect click on everything but element?

前端 未结 1 843
执念已碎
执念已碎 2021-01-12 16:33

On an app with a lot of different components within one component I have a custom Auto-suggest box. The box should be closed if the user clicks anywhere but on the Auto-sugg

相关标签:
1条回答
  • 2021-01-12 16:44
    <button (click)="show = true">show dropdown</button>
    <div #suggestbox *ngIf="show">...</div>
    
    class AutoSuggestComponent {
      bool show = false;
    
      @ViewChild('suggestbox') ElementRef suggestbox;
    
      @HostListener('document:click', [r'$event'])
      onDocumentClick(MouseEvent e) {
        if((suggestbox.nativeElement as HtmlElement).contains(e.target)) {
          // inside the dropdown
        } else {
          // outside the dropdown
        }
      }      
    }
    

    not tested and the button and div element are only a rough approximation of what the component would look like.

    See also How can I close a dropdown on click outside?

    update

    Angular 5 doesn't support global event handlers like document:...

    Use instead the imperative variant

    class AutoSuggestComponent implements AfterViewInit, OnDestroy {
      bool show = false;
    
      @ViewChild('suggestbox') ElementRef suggestbox;
    
      StreamSubscription _docClickSub;
    
      @override
      void ngAfterViewInit() {
        _docClickSub = document.onClick.listen((e) {
          if((suggestbox.nativeElement as HtmlElement).contains(e.target)) {
            // inside the dropdown
          } else {
            // outside the dropdown
          }
        });
      }
    
      @override
      void onDestroy() {
        _docClickSub?.cancel();
      }
    }
    
    0 讨论(0)
提交回复
热议问题