0

I would like to enable/disable a button in LWC depending on if a list variable is empty or not. I know it's possible with a formula in Aura, is it doable in LWC? I have tried the below, but it doesn't work.

        <lightning-layout horizontal-align="space" vertical-align="end">
            <lightning-layout-item padding="horizontal-small" flexibility="grow">
                <lightning-combobox
                    name="objects"
                    label="Objects"
                    value={selectedObject}
                    placeholder="Select Object"
                    options={options.data}
                    onchange={handleObjectChange}
                ></lightning-combobox>
            </lightning-layout-item>
            <lightning-layout-item padding="horizontal-small">
                <lightning-button 
                    variant="brand"
                    label="Add"
                    title="Add object"
                    onclick={handleAdd}
                    class="slds-m-left_small"
                    disabled={empty(options.data)} <------ this line
                ></lightning-button>
            </lightning-layout-item>
        </lightning-layout>
1
  • 1
    LWC, unlike Aura, doesn't have expression functions you can use in markup like empty or if. The logic will need to happen in your JavaScript. – nbrown Nov 5 '20 at 18:56
2

You need to use the property with the get method.

JS

get showButton(){
    return this.options && this.options.data && this.options.data.length;
}

HTML

<lightning-button 
    variant="brand"
    label="Add"
    title="Add object"
    onclick={handleAdd}
    class="slds-m-left_small"
    disabled={showButton}
></lightning-button>
2
  • What determines whether the "showButton" will be updated? Does the component know to watch the "options" variable? – fred Nov 6 '20 at 11:48
  • 1
    The get makes it reactive. when the dependencies are updated it also gets updated. @fred – Rahul Gawale Nov 6 '20 at 12:02

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.