[SalesForce] lightning:select – bind the selected attribute

With reference to this doc – https://developer.salesforce.com/docs/atlas.en-us.lightning.meta/lightning/aura_compref_lightning_select.htm

I read below statement which I am trying to understand-

Also, bind the selected attribute in the new option value and
explicitly set the selected value on the component as shown in the
next example, which ensures that the value on the component
corresponds to the new selected option.

The example provided is :

Component:

<aura:component>
    <aura:attribute name="options" type="List" />
    <aura:attribute name="selectedValue" type="String" default="Red"/>
    <aura:handler name="init" value="{!this}" action="{!c.loadOptions}" />
    <lightning:select name="mySelect" label="Select a color:" aura:id="mySelect" value="{!v.selectedValue}">
        <aura:iteration items="{!v.options}" var="item">
            <option text="{!item.label}" value="{!item.value}" selected="{!item.selected}"/>
         </aura:iteration>
    </lightning:select>
    </aura:component>

Controller:

updateSelect: function(component, event, helper){
    var opts = [
        { value: "Cyan", label: "Cyan" }, 
        { value: "Yellow", label: "Yellow" }, 
        { value: "Magenta", label: "Magenta", selected: true }];
    component.set('v.options', opts);
    //set the new selected value on the component
    component.set('v.selectedValue', 'Magenta'); 
    //return the selected value
    component.find("mySelect").get("v.value");
}

I am trying to understand what was the need to do => component.set('v.selectedValue', 'Magenta'); and how this will be a dynamic option meaning when user select from the drop down how this line would set that particular value instead of setting Magenta. Without doing this I did try to print the option that is being set and saw the result using console.log().

<lightning:select name="mySelect" label="Select a color:" aura:id="mySelect" value="{!v.selectedValue}" onchange="{!c.getNewValue}">

getNewValue: function (component, event, helper) {
 var OptionSel = component.find("mySelect").get("v.value");
 console.log(OptionSel);
}

The above was printing the correct value that I select from the drop each time.

Best Answer

The point of this example is to show you how, with two-way binding, setting the attribute on the component also updated the select list, as well as being about to change the select list value and having it appear in the component's attribute.

Without this setup, you're forced to use find as well as get/set, making your controller code more verbose. The recommended approach is to use attributes to store data the component uses.

Related Topic