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
}
}
}
未经测试,button和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屋!