1

Currently, I am displaying a set of checkboxes on the screen using lightning-checkbox-group, but I need to disable one of the checkbox conditionally. So, looks like we have a 'disabled' attribute in lightning-checkbox-group but when set to true, it disables all the checkboxes. Below is the approach which I tried to disable only 'Second' checkbox, but it is not working:

myComp.html

<template>
    <lightning-checkbox-group name="Checkbox Group"
                              label="Checkbox Group"
                              options={options}
                              value={value}
                              onchange={handleChange}
                              disabled={options.disabled}
                              >
</lightning-checkbox-group>
    
</template>

myComp.js

import { LightningElement, track } from 'lwc';

export default class CheckboxGroupBasic extends LightningElement {
    @track value = ['option1'];

    get options() {
        return [
            { label: 'First', value: 'option1'},
            { label: 'Second', value: 'option2',disabled : true },
        ];
    }

    get selectedValues() {
        return this.value.join(',');
    }

    handleChange(e) {
        this.value = e.detail.value;
        
    }
}

But still it is not disabling the Second checkbox. Any suggestions?

2 Answers 2

2

Don't think its possible to play around with individual checkboxes in <lightning-checkbox-group> </lightning-checkbox-group>, better to use <lightning-input type="checkbox" checked disabled></lightning-input>

As per the documentation

Usage Considerations lightning-checkbox-group is useful for grouping a set of checkboxes. If you have a single checkbox, use lightning-input type="checkbox" instead.

Disabling the complete group using the disabled attribute makes sense because they are treating the group of checkboxes as a single unit.

3
  • Okay, so does that mean I can't disable few checkboxes in a checkbox group?
    – sfdc07
    Commented Apr 3, 2020 at 11:21
  • I think yes! Disabling a checkbox in Checkbox group has to be done using the JSON string that we pass as input, I dont see anything related to that in documentation. Commented Apr 3, 2020 at 11:26
  • Yea Correct.. Then I will use lightning-input tag for the same.. Thank you so much..!!
    – sfdc07
    Commented Apr 3, 2020 at 11:28
-1

I understand that you want your checkbox group will behave like radio button. This solution is working for me:

handleChange(e) {
    const __value = Array.from(e.detail.value)
        .filter((val) => val !== this.value[0]); 
    this.value = __value;
}

You must log in to answer this question.

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