Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

322
Visualizações
Web Components: how to access child component instances from a parent

EDIT I've left out some details in this question, but assume that both of these elements are already defined. Also, in the real world problem, the DOM tree is bigger and the child component is slotted into the parent. There's no issue with finding the child component.

I have two web components: Parent and Child.

I might use these components in markup like this:

<parent-element>
  <child-element></child-element>
</parent-element>

The Child component has logic I want to expose to the parent.

class Child extends HTMLElement {
  constructor() {
    ...
  }

  publicMethod() {
    console.log('call me from the parent component');
  }
}

Ideally, I'd like to call the child method from the parent like this:

class Parent extends HTMLElement {
  constructor() {
    ...
  }

  someTrigger() {
    const child = this.shadowRoot.querySelector('child-element');
    child.publicMethod();
  }
}

This doesn't work, though, since child is an HTMLElement, because the querySelector() API returns an HTMLElement and not the web component instance.

Is there a way I can get the component's instance in a similar fashion? I'd like to be able to traverse the Parent components shadow tree to find a specific component instance.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Be careful with whenDefined;
it tells you the Web Component was defined, NOT when it was parsed in the DOM:

As long as you keep the <child-element> in lightDOM, <slot> and shadowDOM have nothing to do with them.

.as-console-wrapper {max-height:100%!important;top:0;zoom:.88}
.as-console-row:nth-child(n-6) {background:#0057B7!important;color:#FFD500!important}
.as-console-row:nth-child(n+6) {background:#FFD500!important;color:#0057B7!important}
.as-console-row-code{padding:0!important}
<script>
  console.clear();
  class Component extends HTMLElement {
    constructor() {
      super();
      console.log(this.nodeName, "constructor")
    }
    connectedCallback(){
      console.log("connectedCallback", this.nodeName, this.children.length, "children");      
    }
  }
  customElements.define("child-component", class extends Component {
    foo() {
      console.log("Executed <child-element>.foo()");
    }
  });
  customElements.define("parent-component", class extends Component {
    connectedCallback() {
      super.connectedCallback();
      customElements.whenDefined('child-component')
                    .then(() => console.log("Promise resolved, <child-component> IS defined!"));
      setTimeout(() => { // wait till lightDOM is parsed
        console.log("After setTimeout",this.nodeName,"has", this.children.length, "children");
        this.querySelectorAll("child-component").forEach(child => child.foo());
      })
    }
  })
</script>
<parent-component>
  <child-component></child-component>
  <child-component></child-component>
</parent-component>

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda