Search code examples
jquerypolymerweb-frontendpolymer-3.xlit-element

How to querySelect Lit-Element that is within another Lit-Element


Parent element(x-app tag) displaying child1(x-counter),child2(child2-app) elements and whenever there is any change in child1, I would like to update it to child2 as well. So, in the parent I am trying to get the property of child 2 using querySelect but I am getting null value.

ready(){ super.ready();

document.querySelector('x-counter').addEventListener('valueChange',function(e){
  this.b = e.detail;

  const val = document.querySelector('x-app');
  console.log(val.querySelector('child2-app');
  val.a = this.b;


});

}

static get template(){

return html`
  <x-counter></x-counter>
<child2-app></child2-app>

`;

}


Solution

  • Here parent x-app element property share example:

    static get template(){
    
    return html`
      <x-counter  my-property = "{{myProperty}}" ></x-counter>
      <child2-app  my-property = "{{myProperty}}" ></child2-app>
    `;
    }
    

    and below is the x-counter elements inside need to declare (also you need to do the same at child2-app in order to two-way data binding between two child elements).

    use the same property decleration at both x-counter and child2-app elements:

    static get properties() { 
            return { 
              myProperty: {  // my-property will be myProperty (camelCase syntaxt at child)
                notify:true //notify will alove up-side (from child to parent) data bind
    
              }
    }}
    

    So you have myProperty at both child element if you change myProperty element inside of a child this will be effected at other. But be aware, if you use as an object or array of this property. then you may need extra code for obserable changes at both element. example: this.notifyPath('myProperty.name');

    EDIT: Below demo made with lit-element

    DEMO