1

I have a lightning-combobox component, that gets options from a javascript method. What I am trying to do is to get one of those options, as default value in the html component.

Javascript method is something like this:

    get options() {
    var options = [];
        if(this.sortData.sortRules){
            this.sortData.sortRules.forEach(ele =>{
                options.push({label:ele.label + ' ' + ele.direction , value:ele.sortRuleId});
            });
        }
    return options;
    }

The html element is like this:

<lightning-combobox
      name="progress"
      label="Sort:"
      value={value}
      placeholder="Sorting by"
      options={options}
 </lightning-combobox>

I want to know how to get the first option from options[] as default value in the combobox.

Anyone that can help me with this?

1 Answer 1

4

Assuming the options are available in connected callback, you can set a default value like this:

import { LightningElement } from "lwc";

export default class Combobox extends LightningElement {

  options = [{label: 'a', value: 1}, {label: 'b', value: 2}]

  connectedCallback() {
    this.value = this.options[0].value;
  }
}
3
  • It doesn't work in connected callback. The webstore stops working if I'm doing it like this.
    – blanco17
    Jun 30, 2021 at 11:58
  • Then you'll need to do the same when your options are set. You may want to write a setter.
    – Alba Rivas
    Jul 6, 2021 at 9:53
  • Then you'll need to do the same when your options are set. You may want to write a setter.
    – Alba Rivas
    Jul 6, 2021 at 9:53

You must log in to answer this question.

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