Skip to content

Instantly share code, notes, and snippets.

@samuel-alves
Created May 18, 2018 09:56
Show Gist options
  • Save samuel-alves/b6e43a3d88bfaa1af0853002ffdc0962 to your computer and use it in GitHub Desktop.
Save samuel-alves/b6e43a3d88bfaa1af0853002ffdc0962 to your computer and use it in GitHub Desktop.
Alternate/Workaround for contains() function in aura:if Condition in Lightning Component
<aura:component>
<aura:handler name="init" value="{!this}" action="{!c.doInit}" />
<aura:handler name="change" value="{!v.element}" action="{!c.doInit}"/>
<aura:attribute name="items" type="List" />
<aura:attribute name="element" type="String" />
<aura:attribute name="condition" type="Boolean" />
<aura:if isTrue="{!v.condition}">
{!v.body}
</aura:if>
</aura:component>
<aura:component>
<!-- create aura:attribute with list/array type-->
<aura:attribute name="listItems" type="List" default="['Name','Phone']" />
<!-- use 'auraIfWithContains' component with passing item list and contains element name.-->
<c:auraIfContains items="{!v.listItems}" element="Name">
<p><b>yes name is contains in list</b></p>
</c:auraIfContains>
<c:auraIfContains items="{!v.listItems}" element="Email">
<p><b> No Email is not contains in list, so it's not showing</b></p>
</c:auraIfWithContains>
<c:auraIfContains items="{!v.listItems}" element="Phone">
<p><b> yes Phone is contains in list</b></p>
</c:auraIfWithContains>
</aura:component>
({
doInit: function(component, event, helper) {
var getList = component.get('v.items');
var getElement = component.get('v.element');
var getElementIndex = getList.indexOf(getElement);
// if getElementIndex is not equal to -1 it's means list contains this element.
if (getElementIndex != -1) {
component.set('v.condition', true);
} else {
component.set('v.condition', false);
}
}
})
<aura:application extends="force:slds">
<c:auraIfContainsContainer/>
<!-- here c: is org. default namespace prefix-->
</aura:application>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment