0

I'm doing a simple operation wherein I'll disable a button on component based on certain condition. I use queryselector to get the correct button and then disable.

Button HTML:

<div if:true={showButton}>
    <lightning-button variant="brand" label="Disable Me" title="Primary action" onclick={disableButton} class="slds-m-left_x-small disabled-lightning-button"></lightning-button>
</div>

JS:

randomMethod(){
    this.showButton = true;
    var button= this.template.querySelector('.disabled-lightning-button');
    button.disabled = true;
}

The problem here is that when I use conditional rendering on button, it doesn't work. I render the button conditionally and initially the button is hidden. I call a js method when certain criteria is met, in the js method I set the boolean variable that I use for conditional rendering as true and then in the same method, I try to disable the button. The problem occurs only when the button is initially hidden..

when I console button variable, it returns null. Does this mean that querySelector cannot find that button when it's hidden? but isn't it rendered even though it's hidden for now?

Any idea how I can make this to work?

1 Answer 1

2

Until the component is rerendered the new elements are not available. The easiest way is to define another attribute for the disabled status and add that to the button. This is the beauty of the reactive component that you don't have to manually update DOMs.

Define the attribute and set the buttonDisabled the value in the method.

buttonDisabled;
...
randomMethod(){
    this.showButton = true;
    buttonDisabled = true;
}

Add the disabled attribute with the value buttonDisabled to the button.

<div if:true={showButton}>
    <lightning-button variant="brand" label="Disable Me" title="Primary action" onclick={disableButton} disabled={buttonDisabled} class="slds-m-left_x-small disabled-lightning-button"></lightning-button>
</div>

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .