workaround for contains in aura:if

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

Lightning Component

Let us assume there is a situation to check a value in List attribute within Component markup and render the body if the value is present in the List. What do you generally do in this scenario ? You may take advantage of Javascript and do some hack and set one attribute ( may be boolean ) and then do your action. Huh. Why don’t we think in different way ?

Lets see an example with approach we wanted and an alternate approach below:


We have a lightning component, in this component we have a attribute of list of strings

based on the ‘listItems‘ attribute, we need to conditionally render the component body like this :

  • if  listItems list attribute contains or include Name element then display the paragraph (first one)
  • if  listItems list attribute contains or include Phone element then display the paragraph (second one)

OOPS  !! 

Currently, there is NO Expression operators [ contains(), include() ] available in lightning which can check that item are in the list or not. :

Let’s see an awesome way of achieving this and to make it generic.

Step 1 : Create a Lightning Component : auraIfContains.cmp

Component javaScript controller : auraIfContainsController.js 

How to use :
  • Use our custom auraIfWithContains lightning component instead of aura:if to render component body based on list values. You just have to pass the list of items and element to search in this component.
  • If the given value/element present in list then the component body will be rendered. In this case, paragraphs.
Step 2 : Create Lightning Component : auraIfContainsContainer.cmp

Step 3 : Create Lightning Application for Testing:

From Developer Console >> File >> New >> Lightning Application

Output :

check also : How to Change lightning:Icon Color In Salesforce Lightning Component

Wow. It looks to be working great. Thanks for reading this post.

Please like our facebook page for new post updates. & Don’t forget to bookmark this site for your future reference.

if you have any suggestions or issue with it, you can share your thoughts  in comment box.

Happy Learning 🙂

(Visited 3,342 times, 21 visits today)


Leave a Reply