0% found this document useful (0 votes)
181 views40 pages

LWC Imp Concepts V4

This document provides examples of key Lightning Web Component (LWC) concepts including: 1) Basic LWC template and JavaScript usage for one-way binding of data. 2) Two-way data binding between template and JavaScript using the @track decorator. 3) Conditional rendering using if:true and if:false. 4) Iterating over arrays of data in the template using for:each and iterator directives. 5) Component lifecycle hooks like connectedCallback and renderedCallback. 6) Communicating data between parent and child components.

Uploaded by

Vamsi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
181 views40 pages

LWC Imp Concepts V4

This document provides examples of key Lightning Web Component (LWC) concepts including: 1) Basic LWC template and JavaScript usage for one-way binding of data. 2) Two-way data binding between template and JavaScript using the @track decorator. 3) Conditional rendering using if:true and if:false. 4) Iterating over arrays of data in the template using for:each and iterator directives. 5) Component lifecycle hooks like connectedCallback and renderedCallback. 6) Communicating data between parent and child components.

Uploaded by

Vamsi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 40

****************** LWC Concepts*********************

Basic LWC ---

<template>

<lightning-card title=" Hello {word} !!">

<lightning-layout>

<lightning-layout-item size="12" padding="around small">

<lightning-input label="Enter the Name World" value={world} onchange={Hangler}></lightning-


input>

</lightning-layout-item>

</lightning-layout>

</lightning-card>

</template>

JS File -
import { LightningElement,api } from 'lwc';

export default class HelloSetup extends LightningElement {

@api word;

Hangler(event) {

this.word = event.value.target;

--------------------Two-way binding –-------------------

<template>

<lightning-card title="EmployeeInfo">

<div class="slds-m-around_medium">

<p>Employee Name: {name}</p>

<p>Enployee Age: {age}</p>

<p>Employee Salary: {salary}</p>

<lightning-input label="Enter Name" value={name} onchange={nameHandler}></lightning-input>

<lightning-input label="Enter Age" value={age} onchange={ageHandler}></lightning-input>

<lightning-input label="Enter Salary" value={salary} onchange={salaryHandler}></lightning-input>

</div>

</lightning-card>

</template>
JS ---

import { LightningElement,track } from 'lwc';

export default class EmployeeDetailExample extends LightningElement {

@track name;

@track age;

@track salary;

nameHandler(event)

this.name=event.target.value;

ageHandler(event)

this.age=event.target.value;

salaryHandler(event)

this.salary=event.target.value;

-------------If Else Example-------------


<template>

<div if:true={something}>I am true</div>

<div if:false={something}>I am false</div>

</template>

Js

import { LightningElement } from 'lwc';

export default class IfElseExample extends LightningElement {

something=false;

----------IF true and If False--------------

<template>
<template if:true={show}>
<lightning-card title="Employee Information">
<div class="slds-n-around_medium">
<lightning-input label="Enter Name" value={name}
onchange={nameHandler}></lightning-input>
<lightning-input label="Enter Age" value={age} onchange={ageHandler}></lightning-
input>
<lightning-input label="Enter Salary" value={salary}
onchange={salaryHandler}></lightning-input>
<lightning-button label="Save" onclick={saveButtonHandler}></lightning-button>
</div>
</lightning-card>

</template>
<template if:false={show}>
<lightning-card title="Employee Details">
<div class="slds-m-around_medium">
<p>Employee Name: {name}</p>
<p>Employee Age : {age}</p>
<p>Employee Salary : {salary}</p>
</div>
</lightning-card>
</template>
</template>

Js
import { LightningElement,track } from 'lwc';

export default class EmployeeInfo extends LightningElement {


@track name;
@track age;
@track salary;
@track show=true;
nameHandler(event)
{
this.name=event.target.value;
}
ageHandler(event)
{
this.age=event.target.value;
}
salaryHandler(event)
{
this.salary=event.target.value;
}
saveButtonHandler()
{
this.show=false;
}

----------For : Each For: index directive -----------------

<template>

<lightning-card title="HelloForEach">

<ul class="slds-m-around_medium">

<template for:each={contacts} for:item = contact>

<li key={contact.id}> {contact.name},{contact.title}</li>

</template>
</ul>

</lightning-card>

</template>

Js

import { LightningElement } from 'lwc';

export default class HelloForEach extends LightningElement {

contacts=[

{Id:1,

Name:'Amy Taylor',

Title:'VP of Engineering'

},

Id:2,

Name:'Michael Jones',

Title:'VP of Sales'

},

Id:3,

Name:'Jennifer Wu',

Title:'CEO'

},

Id:4,

Name:'Jennifer Anigston',
Title:'VP of Marketing'

},

Id:5,

Name:'Deepika Khanna',

Title:'CTO'

----------------Iterator directive----------------

<template>

<lightning-card title="HelloForEach">

<ul class="slds-m-around_medium">

<template iterator:it={contacts}>

<li key={it.value.id}>

<div if:true={it.first} class="list-first"></div>

{it.value.Name},{it.value.Title}

<div if:true={it.last} class="list-last"></div>

</li>

</template>

</ul>

</lightning-card>

</template>
import { LightningElement } from 'lwc';

export default class HelloForEach extends LightningElement {

contacts=[

{Id:1,

Name:'Amy Taylor',

Title:'VP of Engineering'

},

Id:2,

Name:'Michael Jones',

Title:'VP of Sales'

},

Id:3,

Name:'Jennifer Wu',

Title:'CEO'

},

Id:4,

Name:'Jennifer Anigston',

Title:'VP of Marketing'

},

Id:5,

Name:'Deepika Khanna',

Title:'CTO'

}
]

------Life Cycle Hook -----

<template>

<p>show value : {show}</p>

</template>

import { LightningElement,api } from 'lwc';


export default class Bool extends LightningElement {

@api show=false;

constructor()

super();

console.log('constuctor on the child is called');

connectedCallback()

console.log('connected callback on the child is called');

renderedCallback()

console.log('rendered callback on the child is called ');

disconnectedCallback()

console.log('disconnected callback on the child is called');

}
--------Reactive and nonreactive properties -----------

<template>

<table style="background: white;">

<tr>

<td>

Reactive Private property

<lightning-input type="text" onchange={changeHandler1}></lightning-input>

<br/>

<b>value: {reactivePrivateProperty}</b>

</td>

</tr>

<tr>

<td>

Non Reactive Private property

<lightning-input type="text" onchange={changeHandler2}></lightning-input>

<br/>

<b>value: {nonReactivePrivateProperty}</b>

</td>

</tr>

</table>

</template>

JS -----------

import { LightningElement,track} from 'lwc';


export default class PrivateComponent extends LightningElement {

@track reactivePrivateProperty;

nonReactivePrivateProperty;

changeHandler1(event)

this.reactivePrivateProperty= event.target.value;

changeHandler2(event)

this.nonReactivePrivateProperty=event.target.value;

------------Components communication in LWC ---------


------------Parent To Child Communication - ---------------

Parent component -
<template>
<c-p2c-alert-component
message="Hurray !! I got the data"
card-heading="Parent to Child primitive data communication"
number=20
is-valid
></c-p2c-alert-component>
</template>

import { LightningElement } from 'lwc';

export default class P2cParentComponent extends LightningElement {

Child comp-
<template>
<lightning-card title={cardHeading}>
<div class="slds-notify_alert slds-theme_error" role="alert">
{number} {message} {isValid}
</div>
</lightning-card>
</template>

import { LightningElement, api } from 'lwc';

export default class P2cAlertComponent extends LightningElement {


@api message
@api cardHeading
@api number
@api isValid
}

------------------Parent comp
<template>
<div class="slds-var-m-bottom_medium"></div>
<lightning-card title="Parent to Child communication on action">
<div class="slds-var-m-around_medium">
<lightning-input type="number"
label="Enter percentage"
onkeyup={changeHandler}
value={percentage}
></lightning-input>

<c-p2c-progress-component
progress-value={percentage}
></c-p2c-progress-component>
</div>
</lightning-card>
</template>

import { LightningElement } from 'lwc';

export default class P2cParentComponent extends LightningElement {


percentage=10
changeHandler(event){
this.percentage = event.target.value
}
}
---------------------------Child comp--------------------------
<template>
<lightning-progress-bar value={progressValue} size="large"></lightning-progress-bar>
</template>

import { LightningElement, api } from 'lwc';

export default class P2cProgressComponent extends LightningElement {


@api progressValue
}

Parent component - employeeDetails

<template>

<lightning-card title="Parent to Child Demo">

<lightning-layout>

<lightning-layout-item flexibility="auto" padding="around-small">

<lightning-input label="Enter the Name" onchange={handleChangeEvent}></lightning-input>


</lightning-layout-item>

<lightning-layout-item flexibility="auto" padding="around-small">

<c-child-comp></c-child-comp>

</lightning-layout-item>

</lightning-layout>

</lightning-card>

</template>

import { LightningElement } from 'lwc';

export default class ParentComp extends LightningElement {

handleChangeEvent(event)

this.template.querySelector('c-child-comp').changeMessage(event.target.value);

Child Component –

<template>

Your Name is here: {message}

</template>
export default class ChildComp extends LightningElement {

@track message;

@api

changeMessage(strString)

this.message=strString.toUpperCase();

-------------------Child to Parent communication----------------------

Parent component ----

<template>

<div class="slds-m-around_medium">

Value from Child: {msg}

<c-child-component2 onmycustomevent={handleCustomEvent}><c-child-component2>

</div>

</template>

import { LightningElement,track } from 'lwc';

export default class ParentComponent2 extends LightningElement {

@track msg;
/*constructor()

super();

this.template.addEventListener('mycustomevent',this.handleCustomEvent.bind(this));

}*/

handleCustomEvent(event)

this.msg=event.detail;

<?xml version="1.0" encoding="UTF-8"?>

<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata"
fqn="parentComponent2">

<apiVersion>46.0</apiVersion>

<isExposed>true</isExposed>

<targets>

<target>lightning__AppPage</target>

<target>lightning__HomePage</target>

<target>lightning__RecordPage</target>

</targets>

</LightningComponentBundle>

Child component - -------

<template>

<lightning-card title="Child Component">

<div class="slds-m-around_medium">
<lightning-input name="textVal" label="Enter Text" onchange={handleChange}></lightning-
input>

</div>

</lightning-card>

</template>

import { LightningElement } from 'lwc';

export default class ChildComponent2 extends LightningElement {

handleChange(event)

const name=event.target.value;

const selectEvent=new CustomEvent('mycustomevent',{detail:name,bubbles:true});

this.dispatchEvent(selectEvent);

Data Communication in LWC –


------------Base Lighting component ------------------

Simple record page by base lighting component –

<template>
<lightning-record-form record-id={recordId} object-api-name="Account" layout-
type="Compact" mode="view"></lightning-record-form>
</template>
import { LightningElement,api } from 'lwc';

export default class LoadRecord1 extends LightningElement {


@api recordId;
}

------Custom record Page by Base lighting component---

<template>
<lightning-record-view-form record-id={recordId} object-api-name="Account">
<div class="slds-grid">
<div class="slds-col slds-size_1-of-2">
<lightning-output-field field-name="Name"></lightning-output-field>
<lightning-output-field field-name="Phone"></lightning-output-field>
</div>
<div class="slds-col slds-size_1-of-2">
<lightning-output-field field-name="Industry"></lightning-output-field>
<lightning-output-field field-name="AnnualRevenue"></lightning-output-field>
</div>
</div>
</lightning-record-view-form>
</template>
import { LightningElement,api } from 'lwc';

export default class LoadRecord2 extends LightningElement {


@api recordId;
}

---------Edit record page by base lighting component ---------

<template>
<lightning-record-edit-form record-id={recordId} object-api-name="Contact">
<lightning-output-field field-name="AccountId"></lightning-output-field>
<lightning-input-field field-name ="FirstName"></lightning-input-field>
<lightning-input-field field-name="LastName"></lightning-input-field>
<lightning-input-field field-name="Email"></lightning-input-field>
<lightning-button class="slds-m-top_small" variant="brand" type="submit"
name="update" label="Update"></lightning-button>
</lightning-record-edit-form>
</template>

import { LightningElement,api } from 'lwc';

export default class EditRecord1 extends LightningElement {


@api recordId;
}

------Data Communication in LDS (Lighting data service )------


<template>
<lightning-card title="Create Contact">
<lightning-layout>
<lightning-layout-item size="6" padding="around-small">
<lightning-card title="Create a New contact ">

<lightning-input name="Contact Name " label="Name"


onchange={contactNameChangeHandler}></lightning-input>
<lightning-input name="Contact Email " label="Email"
onchange={contactEmailChangeHandler}></lightning-input>
<lightning-input name="Contact Phone " label="Phone"
onchange={contactPhoneChangeHandler}></lightning-input>
<lightning-button label="Create Contact " onclick={createContact}
variant="brand"></lightning-button>

</lightning-card>
</lightning-layout-item>

</lightning-layout>

</lightning-card>
</template>

import { LightningElement,track } from 'lwc';


import {createRecord} from "lightning/uiRecordApi";

export default class CreateContactLDS extends LightningElement {


@track contactName;
@track contactPhone;
@track contactEmail;

contactNameChangeHandler(event)
{
this.contactName=event.target.value;
}

contactPhoneChangeHandler(event)
{
this.contactPhone=event.target.value;
}
contactEmailChangeHandler(event)
{
this.contactEmail=event.target.value;
}
createContact()
{
const
fields={'LastName':this.contactName,'Phone':this.contactPhone,'Email':this.contactEmail};
const recordInput={apiName:'Contact',fields};
createRecord(recordInput).then(response=>{
console.log('Contact has been created successfully ',response.id);
}).catch(error=>{
console.log('Error in creating contact: ',error.body.message);
});
}
}

Fetch data by apex class

public with sharing class ContactManager {


@auraEnabled(cacheable=true)

public static List<Contact> getContact(){


return [select id,LastName, phone from Contact LIMIT 10];
}
}

import { LightningElement,wire } from 'lwc';


import getAllContacts from '@salesforce/apex/ContactManager.getContact'
export default class FetchContactViaApex extends LightningElement {
@wire(getAllContacts) contacts;
get responseReceived()
{
if(this.contacts){
return true;
}
return false;
}
}

<template>
<lightning-card title="All Contact Records">
<ul>
<template if:true={responseReceived}>
<template for:each={contacts.data} for:item="contact">
<li key={contact.id}>
<div class="slds-p-around_medium lgc-bg">
<lightning-tile label={contact.LastName}>
<p class="slds-truncate" title={contact.Phone}>{contact.Phone}</p>
</lightning-tile>
</div>
</li>
</template>
</template>
</ul>
</lightning-card>
</template>

-------Show toast event------------

<template>
<lightning-card>
<center>
<div class="slds-m-top_medium slds-m-bottom_x-large">
<h2 class="slds-text-heading_medium slds-m-bottom_medium">Show Toast
Notification Demo</h2>

</div>
<lightning-button-group>
<lightning-button label="Show Success" onclick={handleSuccess}></lightning-button>
<lightning-button label="Show Error" onclick={handleError}></lightning-button>
<lightning-button label="Show Warning" onclick={handleWarning}></lightning-
button>
<lightning-button label="Show Info" onclick={handleInfo}></lightning-button>
</lightning-button-group>
</center>
</lightning-card>
</template>

import { LightningElement } from 'lwc';


import {ShowToastEvent} from 'lightning/platformShowToastEvent'

export default class ShowToastEventExample extends LightningElement {

handleSuccess()
{
const showSuccess=new ShowToastEvent({
title:'Success!!',
message:'This is Success Message',
variant:'Success',
});
this.dispatchEvent(showSuccess);
}
handleError()
{
const showError=new ShowToastEvent({
title:'Error!!',
message:'This is a Error Message',
variant:'error',
});
this.dispatchEvent(showError);
}
handleWarning()
{
const showWarn=new ShowToastEvent({
title:'Warning!!',
message:'This is a Warning Message',
variant:'warning',
});
this.dispatchEvent(showWarn);
}
handleInfo()
{
const showInfo=new ShowToastEvent({
title:'Info!!',
message:'This is info Message',
variant:'info',
});
this.dispatchEvent(showInfo);
}
}

------------Navigation service---------

<template>
<lightning-card title="Navigation Service in Lightning Web components">
<lightning-card title="Navigate to Record Pages">
<lightning-button-group>
<lightning-button label="New Record Page"
onclick={navigateToNewRecordPage}></lightning-button>
<lightning-button label="Edit Record Page"
onclick={navigateToEditRecordPage}></lightning-button>
<lightning-button label="View Record Page"
onclick={navigateToViewRecordPage}></lightning-button>
</lightning-button-group> <br/>

</lightning-card>
<lightning-card title="Navigate to List Views">
<lightning-button-group>
<lightning-button label="Account Recent View"
onclick={navigateAccRecentView}></lightning-button>
<lightning-button label="Related List View"
onclick={navigateRelatedListView}></lightning-button>
</lightning-button-group>

</lightning-card><br/>
<lightning-card title="Navigate to Object Page">
<lightning-button-group>

<lightning-button label ="Account Page" onclick={navigateAccObject}></lightning-


button>
<lightning-button label ="Contact Page" onclick={navigateConObject}></lightning-
button>
</lightning-button-group>
</lightning-card> <br/>
<lightning-card title="Navigate to Web Page">
<lightning-button-group>
<lightning-button label ="Web Page" onclick={navigateToWebPage}></lightning-
button>
</lightning-button-group>
</lightning-card>
<lightning-card title="Navigate to Standard Home Tabs">
<lightning-button-group>
<lightning-button label ="Home Page" onclick={navigateToHomePage}></lightning-
button>
<lightning-button label ="Chatter Page"
onclick={navigateToChatterHome}></lightning-button>

</lightning-button-group>
</lightning-card>
</lightning-card>
</template>

import { LightningElement,api } from 'lwc';


import {NavigationMixin} from 'lightning/navigation'
export default class NavigationServiceLWCDemo extends NavigationMixin(LightningElement) {
@api recordId;
navigateToNewRecordPage(){
this[NavigationMixin.Navigate]({
type:'standard__recordPage',
attributes:{
"recordId":this.recordId,
"objectApiName":"Account",
"actionName":"new"
}
});
}

navigateToEditRecordPage(){
this[NavigationMixin.Navigate]({
type:'standard__recordPage',
attributes:{
"recordId":this.recordId,
"objectApiName":"Account",
"actionName":"edit"
}
});
}

navigateToViewRecordPage(){
this[NavigationMixin.Navigate]({
type:'standard__recordPage',
attributes:{
"recordId":this.recordId,
"objectApiName":"Account",
"actionName":"view"
}
});
}

navigateAccRecentView(){
this[NavigationMixin.Navigate]({
"type":"standard__objectPage",
"attributes":{
"objectApiName":"Account",
"actionName":"list"
},
"state":{
"filterName":"Recent"
}
});
}
navigateRelatedListView(){
this[NavigationMixin.Navigate]({
"type":"standard__recordRelationshipPage",
"attributes":{
recordId:this.recordId,
objectApiName:'Account',
relationshipApiName:'Contacts',
actionName:'view'
}
});
}
navigateAccObject(){
this[NavigationMixin.Navigate]({
"type":"standard__objectPage",
"attributes":{
"objectApiName":"Account",
"actionName":"home"
}

});
}
navigateConObject(){
this[NavigationMixin.Navigate]({
"type":"standard__objectPage",
"attributes":{
"objectApiName":"Contact",
"actionName":"home"
}
});
}
navigateToWebPage(){
this[NavigationMixin.Navigate]({
"type":"standard__webPage",
"attributes":{
"url":"https://www.mytutorialrack.com/"
}
});
}

navigateToHomePage(){
this[NavigationMixin.Navigate]({
type:'standard__namedPage',
attributes:{
pageName:'home'
},
});
}
navigateToChatterHome()
{
this[NavigationMixin.Navigate]({
type:'standard__namedPage',
attributes:{
pageName:'chatter'
},
});
}
}

--------Simple interest Calculator- ------------

<template>

<lightning-card title=" Simple interest Calculator">

<lightning-layout multiple-rows>

<lightning-layout-item size="12" padding="around-Medium">

<lightning-input type="number " label=" Enter the principal "

onchange={PrincipalchangeHandler}></lightning-input>

</lightning-layout-item>

<lightning-layout-item size="12" padding="around-Medium">

<lightning-input type=" number" label=" Enter the rate of interest "

onchange={RateofInterrestchangeHandler}></lightning-input>

</lightning-layout-item>
<lightning-layout-item size="12" padding="around-Medium">

<lightning-input type=" number" label=" Enter the Number of year "

onchange={NumberOfyearchangeHandler}>

</lightning-input>

</lightning-layout-item>

<lightning-button label="Simple interest" onclick={simpleSIhnaderler}></lightning-button>

<lightning-layout-item size="12" padding="around-medium">

<lightning-formatted-text value={CurrentOutPut}></lightning-formatted-text>

</lightning-layout-item>

</lightning-layout>

</lightning-card>

</template>

import { LightningElement ,track} from 'lwc';

export default class TestownLWCcaculater extends LightningElement {

@track CurrentOutPut;

principal;

rate;

numberofyear;

PrincipalchangeHandler(event) {

this.principal =parseInt (event.target.value);

}
RateofInterrestchangeHandler(event) {

this.rate = event.target.value;

NumberOfyearchangeHandler(event) {

this.numberofyear = event.target.value;

simpleSIhnaderler()

this.CurrentOutPut = 'Simple Interest is : ' + (this.principal * this.rate * this.numberofyear) / 100;

You might also like