I have a parent component where I am calling a child component twice in LWC.

I am firing an API method in the child from the parent, but it is firing for only one child component, not the other one.

Parent component HTML markup


    // First child component
    <c-child-component><c-child component>

    // Second child component
    <c-child-component><c-child component>

Child @api method

@api handleShowError{

I have made changes in the Playground. You can check here: PlayGround

  • We don't have enough code to help you. As far as I can tell, this shouldn't even compile or run. Can you please create a playground that demonstrates what you're trying to achieve? Please edit the link in to your question. Thanks! – sfdcfox Aug 11 at 6:05
  • @sfdcfox I have updated Playground Link. Please check it. – sanket kumar Aug 11 at 6:48

this.template.querySelector will identify only the 1st component/element. When you need to identify all the components/elements, you need to use querySelectorAll.

You can try below:

this.template.querySelectorAll('c-child').forEach((comp) => comp.showError());

Also for more learning, you can check below links:

  1. https://salesforcesas.home.blog/2019/07/25/lwc-access-templates-and-methods-of-child-components/

  2. https://salesforcesas.home.blog/2019/07/16/lwc-selectors-identification-of-elements/

  • It worked. A slight change in code:- this.template.querySelectorAll('c-child').forEach(comp => comp.showError()); – sanket kumar Aug 12 at 14:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.