简体   繁体   English

Angular 2 Dart:如何检测点击除元素之外的所有内容?

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

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-suggest box (or containing elements of the auto-suggest box). 如果用户点击自动建议框(或包含自动建议框的元素)的任何位置,则应关闭该框。

This is what I would do in jQuery: 这就是我在jQuery中要做的事情:

$(document).on('click','body',function(e) {
if(e.target!='.suggestbox' && $(e.target).parent('.suggestbox').length <1 ) {
$('.suggestbox').remove();
}
});

However In my Angular Dart templates I have: 但是在我的Angular Dart模板中,我有:

index.html: index.html的:

<body>
<my-app>
// sub component
// sub sub component
</my-app>
</body>

I can think of a possibility in detecting a click on the topmost wrapper within the my-app component and send the action to the subcomponent but this is still not a body click. 我可以想到在my-app组件中检测到最顶层包装器上的点击并将操作发送到子组件但是这仍然不是主体点击的可能性。

What is the best way to solve this? 解决这个问题的最佳方法是什么?

<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. 没有经过测试,按钮和div元素只是组件外观的粗略近似值。

See also How can I close a dropdown on click outside? 另请参阅如何在外部单击时关闭下拉列表?

update 更新

Angular 5 doesn't support global event handlers like document:... Angular 5不支持像document:...这样的全局事件处理程序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();
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM