samuel-alves
5/18/2018 - 9:56 AM

Alternate/Workaround for contains() function in aura:if Condition in Lightning Component

Alternate/Workaround for contains() function in aura:if Condition in Lightning Component

<aura:application extends="force:slds">
    <c:auraIfContainsContainer/>
    <!-- here c: is org. default namespace prefix-->
</aura:application>
({
    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: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>
<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>