簡體   English   中英

在模態外部單擊時關閉Angular2模態

[英]Closing Angular2 modal on click outside the modal

這是可以在外部單擊以禁用選擇的示例代碼。 在此示例中,我可以取消選擇,但是只有在單擊元素以激活偵聽器之后才可以。 我想使用此示例隨時關閉模態之外的單擊時的模態。 任何示例將不勝感激。

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=預覽

因此,我有一個示例說明如何處理關閉我創建的自定義下拉菜單,但我相信它也適用於此。

因此,在組件內部:

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
    }
}

因此,它將在button和div之外尋找單擊,但是對於您來說,我只是將.closest()設置為您希望看到關閉的模式。 然后在if語句中關閉模態。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM