How To Iterate List Of Items In LWC
LWC iteration: In this post we will see how to use iteration in Lightning Web Components template. Like aura:iteration in Aura, we have "for:each" in lwc. By using "for:each" we can iterate set of elements/items in lwc html template. We can access element by using for:item and we can get index value with for:index .
Syntax:
<template for:each={itemList} for:item="item" for:index="index">
{item}
</template>
Iteration in lwc html Example: Iterate List of Accounts.
Create apex class: IterationInLwcController
public with sharing class IterationInLwcController {
@AuraEnabled(cacheable = true)
public static List<Account> fetchAccounts(){
return [SELECT Id,Name,Phone,Type,Industry,Rating,Website FROM Account LIMIT 100];
}
}
Create New Lightning Web Component: iterationInLwc
iterationInLwc.html
If you getting list from wired property then, we need o use list.data to "for:each". Because wired property contains data and error.
If you getting list from wired property then, we need o use list.data to "for:each". Because wired property contains data and error.
<template>
<lightning-card title="Iteration In LWC">
<div class="slds-p-around_small">
<template for:each={accounts.data} for:item="account" for:index="index">
<div class="slds-p-left_small" key={account.Id}>
{account.Name}
</div>
</template>
</div>
</lightning-card>
</template>
iterationInLwc.js
import { LightningElement, wire } from 'lwc';
import fetchAccounts from '@salesforce/apex/IterationInLwcController.fetchAccounts';
export default class IterationInLwc extends LightningElement {
@wire(fetchAccounts) accounts;
}
Output:
Nice Post. Keep up the good work Bro!
ReplyDelete