3

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, 2020 at 18:56

1 Answer 1

11

You need to use the property with the get method.

JS

get disableButton(){
    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={disableButton}
></lightning-button>
12
  • 1
    The get makes it reactive. when the dependencies are updated it also gets updated. @fred Nov 6, 2020 at 12:02
  • 1
    Either the logic is backwards here or you've misnamed the getter. In your code, if showButton is true, then disabled is true -- but if you want to show the button, you don't want to disable it. You probably want to rename that getter to disableButton and reverse the logic.
    – jbyrd
    Aug 27, 2021 at 19:14
  • 1
    @jbyrd Makes sense! updated. Aug 28, 2021 at 9:29
  • 1
    I think you'd want return !(this.options && this.options.data && this.options.data.length); ...and then I'll give it an upvote :)
    – jbyrd
    Aug 28, 2021 at 21:18
  • 1
    @jbyrd Yes you are right OP has mentioned that they want to disable when list is empty. Updated the answer. Thanks Aug 30, 2021 at 7:53

You must log in to answer this question.

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