Angular 2 Dart:如何检测点击除元素之外的所有内容?
发布时间:2020-12-17 17:43:02 所属栏目:安全 来源:网络整理
导读:在一个组件中包含许多不同组件的应用程序中,我有一个自定义自动建议框.如果用户点击自动建议框(或包含自动建议框的元素)的任何位置,则应关闭该框. 这就是我在jQuery中要做的事情: $(document).on('click','body',function(e) {if(e.target!='.suggestbox' $
在一个组件中包含许多不同组件的应用程序中,我有一个自定义自动建议框.如果用户点击自动建议框(或包含自动建议框的元素)的任何位置,则应关闭该框.
这就是我在jQuery中要做的事情: $(document).on('click','body',function(e) { if(e.target!='.suggestbox' && $(e.target).parent('.suggestbox').length <1 ) { $('.suggestbox').remove(); } }); 但是在我的Angular Dart模板中,我有: index.html的: <body> <my-app> // sub component // sub sub component </my-app> </body> 我可以想到在my-app组件中检测到最顶层包装器上的点击并将操作发送到子组件但是这仍然不是主体点击的可能性. 解决这个问题的最佳方法是什么? 解决方法<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元素只是组件外观的粗略近似值. 另见How can I close a dropdown on click outside? 更新 Angular 5不支持像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(); } } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- angularjs – Angular JS Touch和Swipe
- angularjs spring mvc json post request
- Bootstrap输入框组件简单实现代码
- 我怎么在bash中source_once?
- 为什么scalac不相信某个方法不符合所需的类型签名?
- 什么是“this”关键字的Scala类型编程类比?
- angularjs – 创建和创建pyobj之间有什么区别?
- twitter-bootstrap – Bootstrap Typeahead没有按预期显示提
- angular – 行为主题vs Observable错误处理
- bash – 在zsh中checkwinsize等价?