Hi Folks, In this blog we will try to understand, How we can iterates over a List using for:each in LWC.
To render a list of items in LWC, We have to use
for:each
directive and to access the current item we have to use for:item="currentItem".
We have to also assign a key to the first element in the nested template, for this we have to use the
key={uniqueId}
directive.In this example we iterates over a list called
conList
, which is defined in the component’s JavaScript class.To get the data, our component wires an Apex method. The Apex method makes a SOQL query that returns a list of contacts as given below:-
public with sharing class IterationAccountController {
@AuraEnabled(cacheable=true)
public static List<Contact> conData(){
return[Select Id,lastName,firstName,Name from Contact ];
}
}
The component’s JavaScript code imports the Apex method and invokes it via the wire service.
iterations_lwc.js
import { LightningElement,wire,track } from 'lwc';
import conData from '@salesforce/apex/IterationAccountController.conData';
export default class Iterations_lwc extends LightningElement {
@track error;
@track conList;
@wire (conData,{}) cntctData({error,data}){
if(data){
this.conList=data;
this.error=undefined;
}
else{
this.error=error;
this.conList=undefined;
}
}
}
The template uses the
if:true
directive to check whether the conList property is truthy. If it is, it iterates over it and renders the name of each contact.iterations_lwc.html
<template>
<lightning-card title="Contact List using for:each" icon-name="standard:contact">
<div class="slds-p-around_medium">
<template if:true={conList} for:each={conList} for:item="con">
<div key={con.Id}>
{con.Name}
</div>
</template>
</div>
</lightning-card>
</template>
iterations_lwc.js-meta-xml
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>55.0</apiVersion>
<isExposed>true</isExposed>
<targets>
<target>lightning__AppPage</target>
</targets>
</LightningComponentBundle>
Output:-
No comments:
Post a Comment