Hi All,
Today we will disscuss very common requirement How to iterate map in Lightning Web Component (LWC) .
sample code:-
Today we will disscuss very common requirement How to iterate map in Lightning Web Component (LWC) .
sample code:-
mapInLWc.html
<template for:each={mapData} for:item="mapKey">
<div key={mapKey.key}>
<div title={mapKey.key}>{mapKey.key}</div>
<div title={mapKey.value}>{mapKey.value}</div>
</div>
</template>
mapInLWc.js
import { LightningElement, wire, track } from 'lwc';
import fetchMapData from '@salesforce/apex/UseMapIterationInLWC.fetchMapData';
export default class LwcMapIteration extends LightningElement {
@track mapData= [];
@wire(fetchMapData)
wiredResult(result) {
if (result.data) {
//mapData = [];
var conts = result.data;
for(var key in conts){
this.mapData.push({value:conts[key], key:key}); //Here we are creating the array to show on UI.
}
}
}
}
UseMapIterationInLWC.apxc
public with sharing class UseMapIterationInLWC {
@AuraEnabled(cacheable=true)
public static Map < String, String > fetchMapData() {
Map < String, String > mapOppAccount = new Map < String, String >();
for(Opportunity oppt : [SELECT ID, Account.Name, Name FROm Opportunity LIMIT 11])
mapOppAccount.put(oppt .Name, oppt .Account.Name);
return mapOppAccount;
}
}
In Lightning Web Components (LWC) the element which is direct child of iterate we need to give them a unique. So when we need to rerender that section LWC use this key to rerender only that section. If we don’t provide a key then LWC will give us an exception Elements within iterators must have a unique, computed key value.
No comments:
Post a Comment