There are use cases, such as the expense tracker app in the Lightning Components Developer's Guide, where users are entering data into a dynamic list that grows with each user input submission. My question is, in these situations, what is the most efficient way to implement a UI element that allows the user to remove an item from the list?
[SalesForce] How to remove items from a dynamic list in Lightning component
Related Topic
- [SalesForce] How does Lightning Component Framework request boxcar’ing affect flows and transactions
- [SalesForce] How to run code when the browser window is resized in a Lightning Component
- [SalesForce] Remove item in dynamic list in Lightning Component
- [SalesForce] Remove item from list in lightning component
Best Answer
Luckily the aura:iteration component has a super convenient, built-in attribute called indexVar. By leveraging indexVar I am able to pass the array index to the controller action, which can then use
Array.prototype.splice()
to remove an element from the list.For example, consider the following aura:iteration element:
I've intentionally included a ui:button and a standard HTML a (anchor) to show how to get the index value in both cases. The controller actions are shown below.
And
helper.removeLead()
is defined as follows: