Wednesday, January 8, 2020

How to iterate over the map in lightning web components

How to iterate over map in lightning web components

This blog post will explain "How to iterate over the map in lightning web components".


mapdemolwc.html


<template>
    <lightning-card>
        <table class="slds-table slds-table_cell-buffer slds-table_bordered">
            <thead>
              <tr class="slds-line-height_reset">
                <th class="" scope="col">
                  <div class="slds-truncate" title="Key">Key</div>
                </th>
                <th class="" scope="col">
                  <div class="slds-truncate" title="Value">Value</div>
                </th>
            </tr>
        </thead>
        <tbody>
            <template for:each={mapkeyvaluestore} for:item="mapkey" for:index="index">
                <tr key={mapkey.key}>
                    <th scope="col">
                     {mapkey.key}
                    </th>
                    <th scope="col">
                      {mapkey.value}
                    </th>
                </tr>
            </template>
        </tbody>
        </table>
    </lightning-card>
</template>


mapdemolwc.js



/* eslint-disable no-console */
/* eslint-disable guard-for-in */
/* eslint-disable vars-on-top */

import { LightningElement, track, wire } from 'lwc';
import getDataFromApex from '@salesforce/apex/mapkeyvalueapexcontroller.methodName';
export default class Mapdemolwc extends LightningElement {
@track mapkeyvaluestore=[];

@wire(getDataFromApex)
getResults(result){
if(result.data){
    for(var key in result.data){
     this.mapkeyvaluestore.push({key:key,value:result.data[key]});
    }

  }
else{
    console.log('some error occured');
  }

 }

}


mapkeyvalueapexcontroller.cls


public with sharing class mapkeyvalueapexcontroller {
    @AuraEnabled(cacheable=true)
    public static map<string,string> methodName(){
        map<string,string> mapkeyvaluestore=new map<string,string>();
        mapkeyvaluestore.put('key1','STORE1');
        mapkeyvaluestore.put('key2','STORE2');
        mapkeyvaluestore.put('key3','STORE3');
        mapkeyvaluestore.put('key4','STORE4');
        mapkeyvaluestore.put('key5','STORE5');
        return mapkeyvaluestore;
    }
    public mapkeyvalueapexcontroller() {

    }
}


lightningapp.app


<aura:application extends="force:slds">
<c:mapdemolwc></c:mapdemolwc>
</aura:application>      

No comments:

Post a Comment