[SalesForce] Remove element from Lightning component

Can I remove one of elements from lightning component with help js controller?

For example from below code I try delete element aura:id="out2".

<aura:component> 
    <div class="slds-align--absolute--center">
        <ui:outputText aura:id="out1" class="slds-text-align--left" value="text1" />
        <ui:outputText aura:id="out2" class="slds-text-align--left" value="text2" />
    </div>
</aura:component>

Best Answer

It's kind of a judgemental call. Basically, there are 2 ways to show hide markup.

Option 1: Using CSS show/hide. This basically means you would use a CSS class to hide the elements in UI but the HTML Markup, attributes will still exist in your DOM(Document object model). In plain technical CSS terms you would add a class property: display: none; https://developer.salesforce.com/docs/atlas.en-us.lightning.meta/lightning/js_cb_show_hide_markup.htm

The advantage of this approach is that if you are basically going to hide 1 or 2 markup elements there is no point in using an aura:if and writing some logic to show/hide it as it will destroy the element and re-create it based on conditions. In CSS show/hide it will just be hidden from UI

Option 2: Using aura:if The use case for this would be let's say you are showing a 3 to 5 step wizard navigation. Basically, like payment cart, you wouldn't want to keep all steps in your component hidden using CSS as the DOM can get quite heavy if each step is going to have like 10 fields and you can never say the user is going to scroll through all 5 steps always. In this case, there is no point in loading all 5 steps together. It's better to lazy load them as and when it's needed. This is a perfect use case for aura:if. Below markup illustrates that and you load each step when the user clicks next button by setting the attribute 'step' as shown below

<aura:if isTrue="{!v.Step == 0}">  
<c:step0comp></c:step0comp></aura:if>

 <aura:if isTrue="{!v.Step == 1}">  
<c:step1comp></c:step1comp></aura:if>


 <aura:if isTrue="{!v.Step == 2}">  
<c:step2comp></c:step2comp></aura:if>

This could kind of like a design pattern that you can follow and put the server side controller in the container component which includes all these steps and just wire them up using events and aura:methods. So all server calls are delegated to server component and the individual data components just act as self-contained steps just taking care of their data and validations.

Hope this helps. Let me know if you need more information.

Related Topic