Adding and Removing Styles on a Lightning Component during runtime.

Adding and Removing Styles  on a Lightning Component during runtime.

 

Hello Trailblazer

Today, I will share article that how you can add or remove the style from the Lightning(Aura) Component during runtime.

You can add or eliminate a CSS style on a part or component during runtime.

Use component.find('myCmp').get('v.class'), where myCmp is the aura, to obtain the component's class name:value of id attribute.

Use the $A.util.addClass(cmpTarget, 'class') and $A.util.removeClass(cmpTarget, 'class') methods to add and remove CSS classes from an element or component.

Component source


<aura:component>
    <div aura:id="changeIt">Change Me!</div><br />
    <lightning:button onclick="{!c.applyCSS}" label="Add Style" />
    <lightning:button onclick="{!c.removeCSS}" label="Remove Style" />
</aura:component>

CSS source


.THIS.changeMe {
    background-color:yellow;
    width:200px;
}


Client-side controller source


{
    applyCSS: function(cmp, event) {
        var cmpTarget = cmp.find('changeIt');
        $A.util.addClass(cmpTarget, 'changeMe');
    },
    
    removeCSS: function(cmp, event) {
        var cmpTarget = cmp.find('changeIt');
        $A.util.removeClass(cmpTarget, 'changeMe');
    }
}


The controller actions that add or remove CSS styles are linked to the buttons in this demonstration.Use $A.util.addClass(cmpTarget, 'class') to add a CSS style to a component.Similarly, in your controller, use $A.util.removeClass(cmpTarget, 'class') to get rid of the class.The component is found by using cmp.find(), which uses the local ID, shown by aura:id="changeIt"

Toggling a Class

To toggle a class, use $A.util.toggleClass(cmp, 'class'), which adds or removes the class.

The cmp parameter can be a component or a DOM element.

To conditionally set a class for an array of components, pass in the array to $A.util.toggleClass().


mapClasses: function(arr, cssClass) {
    for(var cmp in arr) {
        $A.util.toggleClass(arr[cmp], cssClass);
    }
}
Source:- Apex developer guide.

Follow us for more articles on salesforce.

Thanks.
Next Post Previous Post
No Comment
Add Comment
comment url