1

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

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.

| improve this answer | |
  • Fantastic! Works perfectly - and so simple. Helps to have someone else look at code to spot the glitch :) – Irene Apr 8 at 2:42

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.