[SalesForce] $A.util.removeClass not working in some cases

On init of a component, I want to hide an element lightning:buttonIcon if some condition is satisfied(see controller code). In this case it is getting satisfied and I am reaching the code where element is to be hidden(hideElement function in helper). But the element is still visible, on the other hand, if we access the same code (hideElement function) from helper itself like:

this.hideElement(component, id);

It hides the element. What is the reason behind this?

Markup:

<!-- Some code above -->

<div class="slds-p-horizontal--small slds-size--1-of-2 slds-medium-size--1-of-6 slds-large-size--4-of-12">
                <br/>
                <lightning:buttonIcon aura:id="addFieldButtonID" iconName="utility:new" size="large" variant="bare" onclick="{! c.handleFieldDone }" alternativeText="Done!"/>
                <div class="slds-icon_container slds-icon_containercircle">
                    <lightning:icon aura:id="doneFieldIcon" iconName="action:approval" size="xx-small" alternativeText="Done" class="slds-hide"/>
                </div>
                <lightning:buttonIcon iconName="utility:clear" size="large" variant="bare" alternativeText="Remove" onclick="{! c.removeEntry }"/>
            </div>

<!-- some code below -->

Controller:

handleInit : function(component, event, helper){

        if(component.get('v.disableEntryEdit')){
            helper.HideElement(component, 'addFieldButtonID');
        }
}

Helper:

hideElement : function(component, id){
        var element=component.find(id);
        console.log('Element: ' , element.getLocalId()); //gives ID as :addFieldButtonID
        $A.util.removeClass(element, 'slds-show');
        $A.util.addClass(element, 'slds-hide');
        console.log('elementclass: ' , element.get('v.class')); //gives o/p : undefined
    },

Best Answer

Instead of doing things in init, try it in afterRenderer. Reason is that init is called long before DOM availability, which might cause a timing issue.

Incase of afterRenderer it is called only after the DOM is rendered in the view.

Related Topic