加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

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();
  }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读