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).
这就是我在 jQuery 中会做的:
This is what I would do in jQuery:
$(document).on('click','body',function(e) {
if(e.target!='.suggestbox' && $(e.target).parent('.suggestbox').length <1 ) {
$('.suggestbox').remove();
}
});
但是在我的 Angular Dart 模板中,我有:
However In my Angular Dart templates I have:
index.html:
index.html:
<body>
<my-app>
// sub component
// sub sub component
</my-app>
</body>
我可以想到检测对 my-app 组件中最顶层包装器的点击并将操作发送到子组件的可能性,但这仍然不是正文点击.
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.
解决这个问题的最佳方法是什么?
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
}
}
}
未经测试,按钮和 div 元素只是组件外观的粗略近似.
not tested and the button and div element are only a rough approximation of what the component would look like.
更新
Angular 5 不支持像 document:...
Angular 5 doesn't support global event handlers like document:...
改用命令式变体
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();
}
}
这篇关于Angular 2 Dart:如何检测除元素之外的所有内容的点击?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!