Usage of iterator directive in lightning web components

Let’s discuss here how to use the lightning web component HTML template iterator 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 

The iterator directive to iterate over an array. Add  iterator directive to a nested <template> tag that encloses the HTML elements you want to repeat.  To apply a special behavior to the first or last item in a list, use the iterator directive, iterator:iteratorName={array}. Use the iterator directive on a template tag.

Use iteratorName to access these properties:

  • value—The value of the item in the list. Use this property to access the properties of the array. For example,iteratorName.value.propertyName.
  • index—The index of the item in the list.
  • first—A boolean value indicating whether this item is the first item in the list.
  • last—A boolean value indicating whether this item is the last item in the list.

1: Create an Apex Class 

Create an apex class using the following SFDX command

here below is the complete code

 

 

2. Create Lightning web component

 

create a lightning web component using the following SFDX command.

 

In this component, we are using iterator directive to iterate the array and nested array

Use this below foriterator.html markup

 

Use this below foriterator.js code

 

 

Use this below foriterator.css markup

Use this below foriterator.js-meta.xml markup

 

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 iterator:it={accounts.data} and assign a key to the first element in the nested template using the key={it.value.Id}

The below code is used to iterate the nested array of data. This example iterates over an array called iterator:it={accountsInner.data}  and assign a key to the first element in the nested template using the key={it.value.Id} and in the inner template, we are taking the reference from the outer template using terator:it={it.value.Contacts} and iterating the array.