[SalesForce] In lwc lightning-combobox not able to select a value when binded dynamically, If i bind it with hardcoded values then i am able to select it

I am using below code to populate a combobox with dynamic value. But i am not able to select any value and it just gets back to blank value with placeholder text.

HTML Code

enter image description here

<template>
<lightning-card title="Demo Screen"  class="slds--around_medium">   
        <div class="slds-size_1-of-2">
            <lightning-combobox 
                    name="Month"
                    label="Month"
                    value={value}
                    placeholder="Select Month"
                    options={MonthArr} 
                    onchange={handleMonthChange}>
                </lightning-combobox>
        </div>
</lightning-card>
</template>

JS Code

/* eslint-disable no-console */
/* eslint-disable no-alert */
/* eslint-disable no-unused-vars */

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

export default class PaymentScreen extends LightningElement {

    @track MonthArr=[];
    @track isFirstLoad = true;


    connectedCallback() {
        if(this.isFirstLoad)
        {
            console.log('in con call back');
            for(var num = 1;num<=12;num++){
                const option = {
                    label: num,
                    value: num
                };
                this.MonthArr = [ ...this.MonthArr, option ];
            }

       }
    }
}

enter image description here

Best Answer

value needs to be a string for the comparison to match and the combobox to work.


import { LightningElement } from 'lwc';

export default class App extends LightningElement {
    value;
    months;
    connectedCallback() {
        this.months = [...Array(12).keys()]
        .map(k=>({label: `${k+1}`, value: `${k+1}`}));
    }
    handleMonthChange(event) {
        this.value = event.detail.value;
    }
}

Notice the use of ${k+1} to construct a string value from the numeric input. This ensures that the value will match correctly.

Here's the playground for this change.