So, i try to make 2 components (a nav-bar and a custom-menu) communicate with each other, knowing that the menu is not a child of the nav. Inside the nav, I have a burger button and when i press it, i want to display the menu, but I couldnt find a way to trigger a signal in the navcomponent, so that the menu can reach it and change it`s style according to that "signal". The only way I could make it happend was to put the menu in the nav component and work with it there, but I want to make it to be independent. Any ideas how I could make that happen? How to make 2 independent components communicate using Lit?
The best way to do it is using CustomEvents. You need to dispatch the event on the window element in the hamburger @click method, like this:
<my-hamburger
@click="${() => {
window.dispatchEvent(new CustomEvent('hamburger-clicked'));
}">
</my-hamburger>
And you need of course to listen for this event in the custom menu, and you do that by using the connectedCallback method, like this:
connectedCallback() {
super.connectedCallback();
window.addEventListener('hamburger-clicked', this.showMenu); // here you need to pass the function responsible for showing menu
}
disconnectedCallback() {
window.removeEventListener('hamburger-clicked', this.showMenu);
super.disconnectedCallback();
}
What I understand from the description of the code and component structure is as follows:
Navigation Container
nav-bar and custom-menu, both are the child components of Navigation Container. What you can do is you need to trigger a custom event from nav-bar and listen it Navigation Container. Also you need to pass a property in custom-menu to show/hide menu, which will be changed on the basis of the custom event passed to Navigation Container from nav-bar.
import {LitElement, html} from 'lit-element';
// your Navigation Continer
class MyElement extends LitElement {
static get properties() {
return {
showHideMenu: {type: Boolean}, //property to be send in menu component
};
}
constructor() {
super();
this.showHideMenu = false;
}
_handleShowHide(e){
// change showHideMenu property on the basis of recieved value
}
render() {
return html`
<nav-bar
@handleShowHideEvent="${this._handleShowHide}"
>
</nav-bar>
<menu
.showhide=${this.showHideMenu}
></menu>
`;
}
}
customElements.define('my-element', MyElement);
You can refer above code, though there is more to be done apart from this. Like you need to dispatch and handleShowHideEvent event nav-bar (on your menu click) and also you need to read the showhide property in your menu component.