Created
June 29, 2020 18:30
-
-
Save mrigdon-zz/2444f30ee18e4f58a4ae50d81172a411 to your computer and use it in GitHub Desktop.
LWC dismiss on click outside
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<template> | |
<slot></slot> | |
</template> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { LightningElement } from 'lwc'; | |
export default class DismissOnClickOutside extends LightningElement { | |
handleClick = (event: Event) => { | |
const path = event.composedPath(); | |
const inside = path.includes(this.template as any) | |
if (!inside) { | |
this.dispatchEvent(new CustomEvent('dismiss')) | |
} | |
}; | |
connectedCallback() { | |
document.addEventListener('click', this.handleClick); | |
} | |
disconnectedCallback() { | |
document.removeEventListener('click', this.handleClick); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment