How to show or hide particular block in the onclick events in the lightning component
-
I think this a good question where other frameworks like jQuery make it simple with functions like hide and show. Especially in an object oriented framework it seems counter intuitive to have to deal with specific styles on an element to show and hide a component.– Scott MorrisonCommented Jul 28, 2015 at 14:04
4 Answers
The previous reply looks good. You can also use $A.util.toggleClass() markup:
<aura:component>
<ui:button label="Toggle" press="{!c.toggle}"/>
<p aura:id="text">Now you see me</p>
</aura:component>
controller:
({
toggle : function(component, event, helper) {
var toggleText = component.find("text");
$A.util.toggleClass(toggleText, "toggle");
}
})
CSS:
.THIS.toggle {
display: none;
}
First step, create ui:button
<ui:button label="test" press="{!c.doAction}" aura:id="myButton"/>
Next step, add to controller this
({
doAction : function(component, event, helper) {
var button = component.find("myButton");
$A.util.addClass(button.getElement(), 'invisible');
... code
},
})
And you can add new class in STYLE
.THIS .uiButton.invisible {
display: none;
}
Related Salesforce Documentation: Adding and Removing Styles (during runtime)
$A.util.toggleClass() - example above taken from here https://developer.salesforce.com/docs/atlas.en-us.lightning.meta/lightning/js_cb_show_hide_markup.htm does not work as space is missed in css: .THIS .toggle
By the way it works also to show/hide.
.THIS .toggle {
display: block;
}
Use <aura:if/>
to hide and show blocks of markup. This is clearer than adding and removing classes, since it's obvious what is going on when you look at the component markup (rather than trying to figure out what is going on from what is or isn't visible in a long list of classes).
To do this, set an attribute on your component to indicate the mode, then use <aura:if/>
to handle the display:
<aura:component>
<aura:attribute name="showMe" type="Boolean" default="true" />
<ui:button label="Toggle" press="{!c.toggle}"/>
<aura:if isTrue="{!v.showMe}">
<p>Now you see me</p>
</aura:if>
</aura:component>
Then your controller code just sets the value of the attribute:
({
toggle : function(component, event, helper) {
component.set("v.showMe", !component.get("v.showMe"));
}
})
This becomes even more useful if you want to show different content depending on two modes (like toggling between view and edit for a form):
<aura:component>
<aura:attribute name="isEditMode" type="Boolean" default="false" />
<aura:if isTrue="{!v.isEditMode == false}">
<ui:button label="Edit" press="{!c.toggleEditMode}" />
</aura:if>
<aura:if isTrue="{!v.isEditMode}">
<!-- Show the editable version -->
<aura:set attribute="else">
<!-- Show the read-only version -->
</aura:set>
</aura:if>
</aura:component>
See the aura:if Lightning documentation for more information.