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

点点圈 提交于 2019-12-01 05:14:54
<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();
  }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!