2

I have a Lightning Web Component with a radio button group. If I select one, I need to capture the selection and conditionally display a div based on that selection. I can't seem to get it working - what am I missing?

<lightning-radio-group name="myOptions"
    label="My Options"
    options={myoptions}
    value={getSelection}
    type="radio"
    variant="label-inline">
</lightning-radio-group>  
<template if:true={isOption1}>                
    <div class="slds-m-around_medium slds-text-heading_small">
        My conditional display for Option 1
    </div>
</template>
<template if:true={isOption2}>                
    <div class="slds-m-around_medium slds-text-heading_small">
        My conditional display for Option 2
    </div>
</template>

My .js file code around this:

@track optionSelected;

getSelection(event) {
    this.optionSelected = event.detail.value;
    alert(this.optionSelected);
}

get isOption1(){return this.optionSelected == 'Opt1'}
get isOption2(){return this.optionSelected == 'Opt2'}

get myoptions() {
    return [
        { label: 'Option 1', value: 'Opt1' },
        { label: 'Option 2', value: 'Opt2' },
    ];
}

The alert is not being displayed, so it's not getting into the getSelection

1 Answer 1

2

You need to use an onchange handler, not the value attribute, which is used to set the attribute. Here's the corrected version:

<template>
<lightning-radio-group name="myOptions"
    label="My Options"
    options={myoptions}
    onchange={getSelection}
    type="radio"
    variant="label-inline">
</lightning-radio-group>  
<template if:true={isOption1}>                
    <div class="slds-m-around_medium slds-text-heading_small">
        My conditional display for Option 1
    </div>
</template>
<template if:true={isOption2}>                
    <div class="slds-m-around_medium slds-text-heading_small">
        My conditional display for Option 2
    </div>
</template>
</template>

import { LightningElement, track, api } from 'lwc';

export default class App extends LightningElement {
    @track optionSelected;

getSelection(event) {
    this.optionSelected = event.detail.value;
}

get isOption1(){return this.optionSelected == 'Opt1'}
get isOption2(){return this.optionSelected == 'Opt2'}

get myoptions() {
    return [
        { label: 'Option 1', value: 'Opt1' },
        { label: 'Option 2', value: 'Opt2' },
    ];
}

}

And the Playground link.

1
  • Fantastic! Works perfectly - and so simple. Helps to have someone else look at code to spot the glitch :)
    – Irene
    Commented Apr 8, 2020 at 2:42

You must log in to answer this question.

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