简体   繁体   English

在模态外部单击时关闭Angular2模态

[英]Closing Angular2 modal on click outside the modal

This is the Sample code to have click outside to disable the selection. 这是可以在外部单击以禁用选择的示例代码。 In this example I am able to deselect but only after I click on the element to activate the listener. 在此示例中,我可以取消选择,但是只有在单击元素以激活侦听器之后才可以。 I want to use this example to close the modal on click outside of the modal anytime. 我想使用此示例随时关闭模态之外的单击时的模态。 Any example would be appreciated. 任何示例将不胜感激。

activeIndex = 0;

subscription: any;
init$: Subject<any> = new Subject();
stop$: Subject<any> = new Subject();

ngOnInit() {
  let click$ = Observable.fromEvent(document, 'click');

const clickOutside$ = this.init$.flatMap(() => {
  return click$.takeUntil(this.stop$);
});

this.subscription = clickOutside$.subscribe(() => {
  this.activeIndex = null;
  console.log(1);
  this.stop$.next();
});
}

onItemClicked(event, index: number) {
event.stopPropagation()
this.activeIndex = index;
this.init$.next()
}

ngOnDestroy() {
if(this.subscription) {
  this.subscription.unsubscribe();
}
}

http://plnkr.co/edit/lx9eBU?p=preview http://plnkr.co/edit/lx9eBU?p=预览

So I have an example of how I handled closing a custom dropdown that I created but I believe it will work for this as well. 因此,我有一个示例说明如何处理关闭我创建的自定义下拉菜单,但我相信它也适用于此。

So inside of your component: 因此,在组件内部:

openModal() { document.addEventListener('click', this.offClickHandler.bind(this)); }

offClickHandler(event:any) {
    if (!event.target.closest(".select-options") && !event.target.closest(".select-input")) { 
        // do whatever you want here
        // close the modal
        // call document.removeEventListener
    }
}

So that will look for a click outside of button and div, but for you I would just set the .closest() to the modal you want to see closed. 因此,它将在button和div之外寻找单击,但是对于您来说,我只是将.closest()设置为您希望看到关闭的模式。 Then inside the if statement close your modal. 然后在if语句中关闭模态。

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

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