Friday, September 30, 2022

Add a Property to each Object in an Array of Objects with JS in LWC

 


Hi Folks, In this blog we will try to understand, How we can Add a Property to each Object in an Array of Objects with JS in LWC.

Lets suppose we have an array as given below:-

let contactData=[
                   {Name:'Rahul',Age:'31',CreditScore:750},
                   {Name:'Rogers',Age:'28',CreditScore:640}
];

Now let takes a requirement, that if the credit score is more than or equals to 700 then the rating should be 'Hot' or if it is less than the 700 rating should be 'Cold' and then add this property to every object of the Array of Objects that we have. And final output will look like as given below:

[
   {Name:'Rahul',Age:'31',CreditScore:750,rating:'Hot'},
   {Name:'Rogers',Age:'28',CreditScore:640,rating:'Cold'}
]

To achieve this we can use either forEach method or map method. 

Using forEach:

let contactData=[
                   {Name:'Rahul',Age:'31',CreditScore:750},
                   {Name:'Rogers',Age:'28',CreditScore:640}
];
contactData.forEach(element=>{
if(element.CreditScore>=700)
{ element.rating='Hot'; }
else
{
element.rating='Cold'; }
});

console.log('Final Result is:- '+JSON.stringify(contactData));

     

Using map:

let contactData=[
                   {Name:'Rahul',Age:'31',CreditScore:750},
                   {Name:'Rogers',Age:'28',CreditScore:640}
];
let finaldata=contactData.map(x=>{
if(x.CreditScore>=700)
{ return {...x,rating:'Hot'}; }
else
{
return {...x,rating:'Cold'}; }
});

console.log('Final Result is:- '+JSON.stringify(finaldata));

Output in Cosole:-

[
   {"Name":"Rahul","Age":"31","CreditScore":750,"rating":"Hot"},
   {"Name":"Rogers","Age":"28","CreditScore":640,"rating":"Cold"}
]

If you have any comments or queries about this, please feel free to mention them in the comments section below.

Wednesday, September 28, 2022

Call child LWC methods in parent LWC using querySelector





Hi Folks, In this blog we will try to understand how we can call child LWC methods in parent LWC using querySelector

  1. The querySelector() method is a standard DOM API that returns the first element that matches the selector.
  2. Parent component can invoke a child component’s public method as well, for this to work declare the method as public  in child using @api annotation
In this example child LWC exposes increaseCounter()decreaseCounter(), methods by adding the @api decorator to the methods. A parent component that contains c-child ( i.e. our child LWC) can call these methods.

child.html
<template>
   <lightning-card title="Child LWC">                                                                    
<div class="slds-m-around_medium"> {counter} </div> </lightning-card> </template>

child.js

import { LightningElement,api } from 'lwc';

export default class child extends LightningElement {
   counter=0 ;
@api
increaseCounter(){ this.counter=this.counter+1; } @api decreaseCounter() { this.counter=this.counter-1; } }

The parent component contains c-child and has buttons to call the increaseCounter() and decreaseCounter() methods in parent LWC. Here’s the HTML.

parent.html
<template>
   <lightning-card title="Parent LWC">                                                                    
<lightning-button label="Increase Counter" onclick={handleIncrease}> </lightning-button>
<lightning-button label="Decrease Counter" onclick={handleDecrease}> </lightning-button>
<br> <c-child></c-child> </lightning-card> </template>

The handleIncrease() function in parent LWC calls the increaseCounter() method in the c-child element. this.template.querySelector('c-child') returns the c-child element in parent.html. The this.template.querySelector() call is useful to get access to a child component so that you can call a method on the component.

The handleDecrease() function in parent LWC calls the decreaseCounter() method in the c-child element.

parent.js

import { LightningElement } from 'lwc';

export default class parent extends NavigationMixin(LightningElement) {
    handleIncrease() {
        this.template.querySelector('c-child').increaseCounter();
} handleDecrease() {
this.template.querySelector('c-child').
decreaseCounter();
}
}
Output:-

If you have any comments or queries about this, please feel free to mention them in the comments section below.

Navigation Service in LWC



Hi Folks, In this blog we will try to understand how we can use the navigation service, Lightning/Navigation, to navigate to many different page types, such as record, list view, object and lightning component.



To use the navigation service, we should import the lightning/navigation module in the component’s JavaScript class. 
import { NavigationMixin } from 'lightning/navigation';

 Then, Apply the NavigationMixin function to your component’s base class

export default class MyCustomElement extends NavigationMixin(LightningElement){}

To dispatch the navigation request:-

call the navigation service’s [NavigationMixin.Navigate](pageReference,[replace]) function 

this[NavigationMixin.Navigate]({
            type: 'standard__objectPage',
            attributes: {
                objectApiName: 'Account',
                actionName: 'home',
            },
        });


The below example shows that how we can navigate to many different page types, such as record, list view, object and lightning component.

navigation_in_lwc.html

<template>
<lightning-card title="Navigation Service in LWC" icon-name="standard:high_velocity_sales">
<div class="slds-m-around_medium">
<div class="slds-box">
<b>Record: Create,View,Edit</b>
<br>
<lightning-button label="New Contact" onclick={navigateNewContact}>
</lightning-button>
<lightning-button label="View Contact" onclick={navigateViewContact}>
</lightning-button>
<lightning-button label="Edit Contact" onclick={navigateEditContact}>
</lightning-button>
</div>

<div class="slds-box">
<b>Views: Contact Recent List View,Contact related list of account</b>
<br>
<lightning-button label="Contact List View-Recent " onclick={navigateRecentListView}>
</lightning-button>
<lightning-button label="Contact related list of Account" onclick={navigateRelatedLists}>
</lightning-button>
</div>

<div class="slds-box">
<b>Components: LWC, Aura, VF Page</b>
<br>
<lightning-button label="LWC " onclick={navigateToLWC}></lightning-button>
<lightning-button label="Aura" onclick={navigatetToAura}></lightning-button>
<lightning-button label="VF Page" onclick={navigateToVFPage}></lightning-button>
</div>

<div class="slds-box">
<b>Home Page: Account</b>
<br>
<lightning-button label="Account Home Page " onclick={navigateAccountHomePage}></lightning-button>
</div>

<div class="slds-box">
<b>Other: Lightning Page</b>
<br>
<lightning-button label="Lightning Page " onclick={navigateLightningPage}></lightning-button>
</div>

</div>
</lightning-card>
</template>

 

navigation_in_lwc.js

import { LightningElement } from 'lwc';
import {NavigationMixin} from 'lightning/navigation';

export default class Navigation_in_lwc extends NavigationMixin(LightningElement) {
condId='0035g00000fcHNJAA2';
acctId='0015g00000qk5zjAAA';

navigateNewContact(){
this[NavigationMixin.Navigate]({
type:'standard__objectPage',
attributes:{
objectApiName:'Contact',
actionName:'new'
}
})
}

navigateViewContact(){
this[NavigationMixin.Navigate]({
type:'standard__recordPage',
attributes:{
recordId:this.condId,
actionName:'view'
}
})
}

navigateEditContact(){
this[NavigationMixin.Navigate]({
type:'standard__recordPage',
attributes:{
recordId:this.condId,
actionName:'edit'
}
})
}

navigateRecentListView(){
this[NavigationMixin.Navigate]({
type:'standard__objectPage',
attributes:{
objectApiName:'Contact',
actionName:'list'
},
state: {
filterName: 'Recent'
}
})
}

navigateRelatedLists(){
this[NavigationMixin.Navigate]({
type:'standard__recordRelationshipPage',
attributes:{
recordId:this.acctId,
objectApiName:'Account',
relationshipApiName: 'Contacts',
actionName: 'view'
}
})
}

navigateToLWC(){
var compDefinition = {
componentDef: "c:mock_ui_parent",
}

// Base64 encode the compDefinition JS object
var encodedCompDef = btoa(JSON.stringify(compDefinition));

this[NavigationMixin.Navigate]({
type:'standard__webPage',
attributes:{
url: '/one/one.app#' + encodedCompDef
}
})
}

navigatetToAura(){
this[NavigationMixin.Navigate]({
type: "standard__component",
attributes: {
componentName: "c__auraComponent" //auraComponent is the name of the
component
},
//If you need to pass some data to the destination component, you have to
provide it to the key "state" as an object.
state: {

//c__Value: '100'
}
});
}

navigateToVFPage(){

this[NavigationMixin.GenerateUrl]({
type: 'standard__webPage',
attributes: {
url: '/apex/myVFPage'
}
}).then(generatedUrl => {
window.open(generatedUrl);
});

}

navigateAccountHomePage(){
this[NavigationMixin.Navigate]({
type:'standard__objectPage',
attributes:{
objectApiName:'Account',
actionName:'home'
}
})

}

navigateLightningPage(){
this[NavigationMixin.Navigate]({
type: 'standard__navItemPage',
attributes: {
apiName: 'LWC_Components'
},
});
}
}


 navigation_in_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:-


If you have any comments or queries about this, please feel free to mention them in the comments section below.