简体   繁体   中英

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

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. Then inside the if statement close your modal.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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