简体   繁体   中英

how to get reference to the element hidden in lwc?

I am learning lwc and I came across this problem. I have the following code.

html:

<template if:true={showLayout}>
   <template if:true={showAllTabs}>
      <div class="tab-container">
         <div class="left-arrow">
             'Left icon code'         
         </div>
         <ul class="slds-tabs_default_nav tab-list">
            'li elements to disply the tabs'
         </ul>
         <div class="right-arrow">
             'Left icon code'         
         </div>
      </div>
   </template>
</template>

I am trying to get the reference of the ul element and right-arrow div in javascript to decide whether right navigation arrow should be shown or not based on scroll available on ul element. But, I am unable to get the reference of these 2 elements. I know that they are hidden thats why I am not able to find the reference. But, how to overcome this issue. I tried to get the reference in renderedCallback() and in the function where showAlltabs becomes true, nothing worked.

JS:

renderedCallback(){
   let tabList = this.template.querySelector('.tab-list');
   let rightArrow = this.template.querySelector('.right-arrow');
}

handleLayoutOpen(){
   this. showAllTabs = true;
   let tabList = this.template.querySelector('.tab-list');
   let rightArrow = this.template.querySelector('.right-arrow');

}

In both function I get undefined for both the elements.

Went through this developer guide https://lwc.dev/guide/html_templates#render-html-conditionally , nothing is mentioned about template reference here.

PS: I am very new to LWC, please be kind in your answer.

I was able to find a alternate solution to this problem. I used slds-hide and slds-show classes, instead of if:true.

<div class='slds-hide'>
   <div class='slds-hide'>
      <div class="tab-container">
         <div class="left-arrow">
             'Left icon code'         
         </div>
         <ul class="slds-tabs_default_nav tab-list">
            'li elements to disply the tabs'
         </ul>
         <div class="right-arrow">
             'Left icon code'         
         </div>
      </div>
   </div>
</div>

In JS I used Element.classList.add() and Element.classList.remove() methods to show and hide the divs whenever I need.

NOw I am able to get the reference of the hidden elements as they are not truly absent in the dom.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM