[SalesForce] How to reset attribute value to null in Lightning Component

I'm trying to reset an attribute value to null. But when I execute reset button call, the value in the textbox is cleared BUT it does not get cleared from display.

Here is a sample code.

TestCmp

<aura:component implements="flexipage:availableForAllPageTypes" access="global">

    <aura:attribute name="num" type="Integer" default="" />

    <div class="slds-card slds-p-around_small">

        <div class="slds-grid slds-gutters">
            <div class="slds-col slds-size_1-of-1">
                <lightning:input aura:id="numDays" type="number" value="{!v.num}" min="0" placeholder="days..." label="Number value" />
            </div>
        </div>
        <div class="slds-grid slds-gutters slds-grid_align-center slds-p-top_medium">
            <div class="slds-col">
                <lightning:button label="Reset (null)" onclick="{!c.reset1}" variant="brand" />
            </div>
            <div class="slds-col">
                <lightning:button label="Reset ('')" onclick="{!c.reset2}" variant="brand" />
            </div>
            <div class="slds-col">
                <lightning:button label="Reset (0)" onclick="{!c.reset3}" variant="brand" />
            </div>
        </div>

    </div>

</aura:component>

TestCmpController.js

({
    reset1 : function(component, event, helper) {
        component.set("v.num", null);
    },
    reset2 : function(component, event, helper) {
        component.set("v.num", "");
    },
    reset3 : function(component, event, helper) {
        component.set("v.num", "0");
    }
})

If you try the code above. You will notice that the <lightning:input> has a placeholder text. This is a requirement for my project.

There I've added 3 Reset buttons, each execute to empty the attribute value. Now, to support placeholder text, I need to clear the value itself, and if I simply reset it to 0, then placeholder text won't show up.

Strangely enough, after clicking Reset (null) or Reset ('') buttons, the display of component still shows the number value. But if we simply click inside the input textbox then it shows placeholder text and clear the displaying value.

Doesn't it look like a bug in lightning:input? Is there any workaround for me to try on?

Best Answer

lightning:input is still in beta. You can use this component but its unstable, so the below code gives an error if there is an lightning:input component in the component markup.

$A.get('e.force:refreshView').fire();

Use ui:inputText component, so declare this component like below:

<ui:inputText aura:id="numDays" value="{!v.num}" placeholder="days..."/>

And using the below code, the value inside the component gets cleared and you will be able to see the placeholder

component.set("v.num", "");
Related Topic