Usage of for:each template directives in Lightning web components

Let’s discuss here how to use the lightning web component HTML template for:each directive to iterate through the collection of data. The power of Lightning Web Components is the templating system, which uses the virtual DOM to render components smartly and efficiently. As the name suggests, the attribute directives are altering the properties of an element to which they are attached and the structural ones are changing. Directives are special HTML attributes, like if:true and for:each, that gives you more power to manipulate the DOM in markup.HTML templates also render data to the DOM.  Please refer to this link for the development environment setup 

To render a list of items, use for:each directive or the iterator directive to iterate over an array. Add the directive to a nested <template> tag that encloses the HTML elements you want to repeat. Regardless of which directive you use, you must use a key directive to assign a unique ID to each item. When a list changes, the framework uses the key to rerender only the item that changed. The key in the template is used for performance optimization and isn’t reflected in the DOM at run time. When using the for:each directive, use for:item="currentItem" to access the current item.  To assign a key to the first element in the nested template, use the key={uniqueId} directive.

1: Create an Apex Class 

Create an apex class using the following SFDX command

here below is the complete code and this class will get the list of accounts that will be displayed in UI.

 

2. Create Lightning web component

create a lightning web component using the following SFDX command.

In this component, we are using for each to render the list and the nested list also.

Use this foreach.html markup

 

use the below foreach.js code

use the below foreach.css

 

use the below code for foreach.js-meta.xml

 

3. Push changes to scratch org.

Push changes to scratch using this command and add this component to record page using lighting app builder

After adding the lightning web component to record page using the app builder. you can able to see the data as shown below and one section contains the simple collection and another section contains the nested collections.

 

Understand the code 

The below code is used to iterate the array of data.  This example iterates over an array called accounts.data and assigning each element in the array to for:item value and assign a key to the first element in the nested template using the key={acc.Id} 

 

The below code is used to iterate the nested array of data. This example iterates over an array called accountsInner.data and assigning each element in the array to for:item value and assign a key to the first element in the nested template using the key={acc.Id} and in the inner template we are taking the reference from the outer template for:item and using the iteration using the for:each={acc.Contacts} .