alfredopacino
alfredopacino

Reputation: 3241

Passing data between components in Polymer 3

I have 3 components: a mainComponent, a SideMenu, and ContentArea (both children of mainComponent). I want to make ContentArea see the changes of popupOpen value.

The function togglePopup() simply toggle the popupOpen boolean value.

In more details: I pass this function as property from mainComponent to SideMenu. The function changes popupOpen value, but this change isn't reflected in ContentArea.

mainComponent

class mainComponent extends LitElement {
    constructor(){
        super()
        this.popupOpen = false
    }
    togglePopup() {
        console.log("togglePopup from main comp");
        this.popupOpen = !this.popupOpen
        this.requestUpdate();
    }

    render(){
        return html`
<div>
   <side-menu .togglePopup='${this.togglePopup}' popupOpen="${this.popupOpen}"></side-menu>
   <content-area popupOpen="${this.popupOpen}"></content-area>
</div>
`
    }
}

SideMenu

class SideMenu extends LitElement {
    constructor(){
        super()
    }
    static get properties(){
        return {
            popupOpen: Boolean
        }
    }
    render(){
        return html`
    <section id="side-menu">
            <a @click="${this.togglePopup}" >Add contact</a>
    </section>
`
    }

}

ContentArea

class ContentArea extends LitElement {
    constructor(){
        super()
    }
    static get properties(){
        return {
            popupOpen: Boolean
        }
    }
    render(){
        return html`
<section id="content-area">
<p>POPUP VALUE: ${this.popupOpen}</p>  <!-- this value doesn't change! -->  
</section>
`
    }

}

Upvotes: 0

Views: 314

Answers (1)

Cappittall
Cappittall

Reputation: 3441

In order to fire togglePopup function properly, try:

<side-menu .togglePopup='${e=> this.togglePopup()}' .popupOpen="${this.popupOpen}"></side-menu>

instead :

<side-menu .togglePopup='${this.togglePopup}' .popupOpen="${this.popupOpen}"></side-menu>

Demo

Upvotes: 2

Related Questions