Thursday 25 August 2022

Lifecycle hooks in LWC

There are 3 phase of LWC component 

1. Mounting 
A. constructor, B. connnectedCallback C. render D. renderedCallback

2. UnMounting 
A. disconnectedcallback

3. Error 
A.errorcallback

Note - render is not lifecycle hook, it is protected method of Lightning element class.

Mounting Phase

LWC Creation and Render Life cycle




















Constructor Method
·       This method called when component is instantiated and It flows from parent to child component.
·       Need to call Super() inside constructor method
·       Can’t access any component properties or child component because it’s not ready yet.
·       Host element can be accessed through “this. template” inside constructor method.
·       Don’t add any attributes to host inside constructor

C constructor(){
        super(); // This is mandatory
        console.log('parent component constructor called ');
        //var elements = this.template.querySelector('.demo'); // We cant do this coz component
is not loaded yet. however we can add event listener to whole component
       // console.log('elements..',elements);
    }

connectedCallBack Method
·       This method called when component is inserted into DOM and It flows from parent to child component.
·       Can’t access any  child component property because it’s not exists yet.
·       Host element can be accessed through “this. template” inside this method.
·       Use connectedCallBack to perform initialization task such as fetch data, set up caches,listen to publish-subscribe events or call apex method.
Dont use this method to change the state of component properties loading values or setting properties. Use getters and setters instead.

connectedCallback(){
        console.log('parent component connectedCallback called ');
       
 }
renderedCallback Method
·       This method called when component is rendered and It flows from child to parent component.
·       It can fired more than once, any changes made to component invokes this method again and again which impact performance
·      When component re-renders all expression used in the template are reevaluated 
·       Don’t use renderedCallback to change the state or update property of a component
Do not use rerenderedCallback to update wire adapter configuration object property, it will result infinite loop.

renderedCallback(){
        console.log('parent component renderedCallback called ');
       
}

UNMounting Phase

disconnectedCallback Method
·       This method called when component is removed from DOM
·       
It flows from Parent to child and it is specific Lightning Web component.

disconnectedCallback(){
        console.log('parent component disconnectedCallback called');
    }

Uses
1. disconnectedCallback can be used for performance improvement and memory leakage issue.
for example, If event listener or set Interval of window property set,
then It will be running behind the scene, we can remove (removeEventlistner or clearInterval)
in this method.

Error Phase

disconnectedCallback Method
This method called when  descended component throw an error.
errorCallBack have 2 arrgurment error object and stack argument as String

errorCallback(error,stack){
        console.log('stack',stack);
        console.log('error',error);
        console.log('error message',error.message);
 }

render Method
  • render method is a protected method of Lighting Element Class.
  • This method tells the lightning engine which template to load based on some condition, The return type of this method is reference of template.
  • We dont have to keep writing all html code in html file, we can segregate to different html file. By using render method we can load. 
 Importing html file.
import secondHTML from './second.html';
import firstHTML from './first.html';

render(){

        return this.htmlFileName === 'secondHTML' ? :firstHTML;
       
    }




Friday 1 July 2022

How to map relationship query results to Lighting Data Table ?

We can not straight forward map relationship filed from apex to LWC data table. When we get query results related object information comes  as different object itself. So we need to traverse the query results and map the way we want to.

Hers is your controller method
@AuraEnabled(cacheable=true)
    public static List<Associated_Healthcare_Center__c> getAssociatedFacility(Id sLeadId,Id sAccountId){
       
    return [SELECT id,Signature_Healthcare_Center__c,Signature_Healthcare_Center__r.phone__c,
                 Signature_Healthcare_Center__r.Facility_Short_Name__c,
                 Signature_Healthcare_Center__r.Admission_Director__r.Name
                 FROM Associated_Healthcare_Center__c WHERE Account__c =:sAccountId 
                 Order By Signature_Healthcare_Center__r.Facility_Short_Name__c];
          
       
    }

Template Data table code 
      <div style="height: 300px;">
            <lightning-datatable
                    key-field="Signature_Healthcare_Center__c"
                    data={data}
                    columns={columns}>
            </lightning-datatable>
        </div>

Template Java script code.
import { LightningElement,api,wire,track} from 'lwc';
import getAssociatedFacility from '@salesforce/apex/AssignFacilityLWCController.getAssociatedFacility';

const columns = [
    { label: 'Facility', fieldName: 'Facility' },
    { label: 'Admission Director', fieldName: 'AdmissionDirector', type: 'text' },
    { label: 'Phone', fieldName: 'Phone', type: 'phone' },
    
];
export default class AssignFacilityLWCModal extends LightningElement {
    @api recordId;
    @api accountId;
   
    @track data;
    @track columns = columns;
    @track error;

    /*connectedCallback() {
       console.log('Inside chield component record Id -->',this.recordId);
       if(this.recordId){
           getAssociatedFacility({sLeadId:this.recordId,sAccountId:this.accountId})
            .then(result=>{
                console.log('result-->',result);
            }).catch(err => {
                console.log('err',err)
                this.showError(err.message);
            });

       }
       
    }*/
    @wire(getAssociatedFacility,{sLeadId:'$recordId',sAccountId:'$accountId'})
    getAssociatedFacilityWired({ error, data }) {
        if (data) {
            
            
               let tempRecords = JSON.parse( JSON.stringify( data ) );
                    tempRecords = tempRecords.map( row => {
                    return { ...row, Facility: row.Signature_Healthcare_Center__r.Facility_Short_Name__c,
AdmissionDirector: row.Signature_Healthcare_Center__r.Admission_Director__r.Name
Phone: row.Signature_Healthcare_Center__r.Phone__c };
                });
                 console.log(' this.datempRecordta-->'this.tempRecords);
                this.data = tempRecords;
           
            this.error = undefined;
        } else if (error) {
            this.error = error;
            this.data = undefined;
        }
    }

In Console this is how query results will be shown before mapping

Here is actual Output




Tuesday 3 May 2022

Style in LWC

 Following are the ways we can apply in CSS in LWC.

1. Inline CCS

Inline CSS is not recommended approaches, it is take highest priority among all CSS. style="color:green;font-size:10px;" is inline CSS added to div
<template>
    <lightning-card title="Inline CSS">
        <div>
            <div style="color:green;font-size:10px;">This is inline Style div</div>
        </div>
    </lightning-card>
</template>

 2. External CSS
style can be applied to an elements such as h1, p,div span etc.
It can applied to class using "." notation. for example .user{}
It can also be applied to pseudo class.  for example .user:hover{}
Id locator is not being used in LWC to apply style

To apply external css, need to create separate CSS file, file name should be exactly matched with component name. for example - If component name is externalCSS then file name should be "externalCSS .css"

<template>   
    <lightning-card title="External CSS">
        <div>
            <div class="externalDiv">This is External Style div</div>
            <p> This is a p Tag</p>
        </div>
    </lightning-card>
</template>

CSS File.
.externalDiv{
    background-color: yellow;
    color:blue;
    font-size:20px;
}
p{
    color:green;
    font: size 20px;
    border: 1px solid red;
}
.externalDiv:hover{
    background-color: white;
    color:red;
    font-size:50px;
}

3. Lightning Design System.
Its a salesforce standard style library.- https://www.lightningdesignsystem.com/
slds-var-p-horizontal_medium. Few more examples margin,grid,batch,text style,box,brand. 
We can search what CSS/stylesheet code needed, copy pseudo code

<template>
    <lightning-card title="SLDS">
        <div class="slds-var-p-horizontal_medium">
            <div class=" slds-box ">
                <p>This is a regular-sized box.</p>
                <span class="slds-badge">Badge Label</span>
                <span class="slds-badge slds-theme_success">Badge Success</span>
              </div>
        </div
       
    </lightning-card>
    <lightning-card>
        <div class="slds-brand-band slds-brand-band_medium slds-brand-band_group"></div>
    </lightning-card>

</template>

4.  Design Token.
Design tokens are the visual design atoms of the design system — specifically, they are named entities that store visual design attributes. We use them in place of hard-coded values (such as hex values for color or pixel values for spacing) in order to maintain a scalable and consistent visual system for UI development.
Note - Only global action design token can be used in salesforce platform for styling.
Instead of using hard code value we can use token. for example. To have blue text color and white background we can define CSS like 
div{
    color: var(--lwc-brandTextLink);
    background:var(--lwc-brandPrimaryTransparent);
}

5. Shared CSS
When we have common CSS code which are required to be used in multiple components at that time shared CSS is expected to be used. this approach will  code redundancy and easy to maintain.

Assume we have 2 components, component 1 and component 2. both components have common CSS code along with individual CSS code.
 Step - 1 : Create a LWC component named as sharedCSSLWC.
Step -2 : Delete html and JS file from component bundle
Step - 3 : Create CSS file named as sharedCSSLWC.css
Step- 4 : Add common CSS code.
Step - 5 : Go to CSS file of component 1 and import sharedCSSLWC
Step - 6   Go to CSS file of component 2 and import sharedCSSLWC

SharedCSSLWC.css
.mainDiv{
    width:100%;
    background-color: #ddd;
}
.internalDiv{
    text-align:right;
    padding-top:10px;
    padding-bottom: 10px;
    color:white;
}
Component1.css
@import 'c/sharedCSSLWC';
.p{
    width:90%;
    background-color:green;
}
Component2.css
@import 'c/sharedCSSLWC';
.css{
    width:80%;
    background-color:#2196f3;
}

6. Dynamic Styling
Sometime we have assign CSS dynamically. To do so we need to use getter. Assume on user input div width will be controlled. 
There is an input box where percentage will be entered, based on entered value div width will be visible accordingly. 
style={percentage} is the getter.

<template>
    <lightning-card title="Dynamic CSS">

        <div class="slds-var-m-around_medium">
            <lightning-input label="Percentage" type="Number"
                onkeyup={changeHandler} value={percent}>

            </lightning-input>
            <div  style={percentage} class="slds-notify slds-notify_alert slds-theme_alert-texture slds-theme_error" role="alert">
                This is an alert !!!
            </div>
        </div>
    </lightning-card>

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

export default class DynamicCSS extends LightningElement {
    percent=10;
    changeHandler(event){
        this.percent = event.target.value;
    }

    get percentage(){
        return `width: ${this.percent}%`;
    }
}

7. Styling Across Shadow DOM
This is required when we need to override standard salesforce style. this is not advisable though. We need to follow this when there is no option left. This will have performance impact.

As per shadow dom concept CSS code will not cross boundary even if we apply CSS code externally it will not reach to shadow DOM, it will be applied to parent component. To apply CSS code we need to generate css code from Java script. here is sample code.

Here is component code, It only contains one button. I want to apply CSS to that button. Tried with external CSS by assign class. That class applied only outer element. It could not reach to shadow DOM <button>
<template>
    <lightning-card title="Shadow DOM">

        <div class="slds-var-m-around_medium">
            <lightning-button label="Test" title="Test" class="btnCSS></lightning-button>
        </div>
    </lightning-card>

</template>

To apply CSS to shadow DOM
shadow-d-o-m-l-w-c - component name referenced in kebab case.
Below code will create inline <style> //here css code  </style>tag inside button.
import { LightningElement } from 'lwc';
export default class ShadowDOMLWC extends LightningElement {
    isLoaded = false;
    renderedCallback(){
        if(this.isLoaded) return;
        const style = document.createElement('style');
        style.innerText = `c-shadow-d-o-m-l-w-c .slds-button{
            background: red;    
            color:white;
        }`;
        this.template.querySelector('lightning-button').appendChild(style);
        this.isLoaded = true;
    }
}

Tuesday 19 April 2022

How to access Elements in LWC?

 To access elements rendered by component we need to use template property.

Access element from tag. <h1>Element Inside H1 Tag </h1>
const h1Element = this.template.querySelector('h1');
Console.log(h1Element.innerText ); // It will print "Element Inside H1 Tag"

We can apply style sheet after getting DOM element dynamically. 
h1Element.style = 'color:red;border-style: solid;'

Accessing element using class.
const userElements =  this.template.querySelectorAll('.name');
It will return node list (multiple items that is why  querySelectorAll is being used.)

We can set attributes to each element of node list dynamically or apply style sheet.
Array.from(userElements).forEach(item=>{
            console.log(item.innerText);
            item.setAttribute('title',item.innerText);
            item.style = 'background-color: black;'
        })

Note - Dont use Id selector with query selector in LWC

What is the use of lwc:dom = 'manul'
When we want to append html element dynamically to an element from JavaScript at that time lwc:dom directive required. it just tell LWC engine that html element going to added dynamically.

 <div class="childElement" lwc:dom="manual"> </div>

 const childELement = this.template.querySelector('.childElement')
        childELement.innerHTML = '<p>I am a Child DOM</p>';

What is shadow DOM?

 What is DOM ?

DOM - Document Object Model is a programming API for HTML or XML component, It defines logical structure of documents and the way document is accessed and manipulated. Basically the DOM is tree structure representation of web page.

What is Shadow DOM ?

Shadow DOM brings encapsulation concept to DOM. It enables to link hidden separate DOM to an element.

Benefits: DOM query, CCS rules and event propagation does not cross shadow boundary, hence creating encapsulation.

Basically when we try fetch all the DOM using query selectors, we will not get DOM elements for child component in parent component.

When we apply style sheet to DOM of parent component, there will be no impact to child component DOM.

Event propagation will not work from child to parent or vice versa by default. 

How to attach shadow DOM to element ?

<script>

    const element = docuement.queryselector('#elementId');

    const shadowRoot = element.attachShadow({mode:'open'});

    shadowRoot.innerHTML = '<p>I am a shadow DOM</p>'

</script>

How to invoke one LWC component from another ?

 Adding one LWC component within body of another LWC component  is known as component composition. It allows building complex component from simper building block component.

How to refer child component from parent component ?
1. childComponent            <c-child-component></c-child-component>

2. childComponentDemo       <c-child-component-demo></c-child-component-demo>

3. childComponentLWC         <c-child-component-l-w-c></c-child-component-l-w-c>

This naming convection known as kebab case. Replace capital letter with small and prefixed with hypen.

Advantages - Defining smaller component will make testing easy and reusability. 

Tuesday 5 April 2022

Template Looping in LWC

 There are 2 types of template looping in LWC

1. for:each
2. iterator

For Each
<template for:each={array} for:item="currentItem" for:index="index">
// we can add repeatable components
</template>

Note- 
1. for:each attribute take array as input
2. for item represent the current item of the loop, currentItem is the alias name, we can name to anything.
3. for:index holds index of current element of an array.

Importance of Key attribute in Template loop
Key is a special string/integer attribute required to be included to first element inside template when creating list of elements.
Key help LWC engine to identify which items added,removed or modified.
Key must be string or integer, It cant be object.
Array Index cant be defined as key.

<template>
    <lightning-card title="Best Companies">
        <div class="slds-m-around_medium">
            <template for:each={companyList} for:item="company">
                <ul key={company} class="slds-has-dividers_around-space">
                    <li class="slds-item">{company}</li>            
                    </ul>
            </template>
        </div>
    </lightning-card>
</template>
java script 
import { LightningElement } from 'lwc';

export default class Looping extends LightningElement {
    companyList = ['Google','Meta','Amazon','Salesforce','Signature Healthcare']
}

Iterator
To apply special behavior to the first or last element of list, iterator is preferable over for: each.
<template iterator:iteratorName={array}>
// here is repeating elements
</template>

Note
1. Iterator is a keyword to tell LWC engine its iterator loop.
2. IteratorName is the alias name, holds current element of array.
3. array is data on which loop is going to be executed.

Properties of Iterator
Value- the value of item of the array. Use this property to get array properties. Iteratorname.value.propertiesname
index: index of current item of array. iteratorname.index
first: Boolean(true/false) value indicates whether element is the first element of array. iteratorname.first
last: Boolean value indicates whether element is the last element of array. iteratorname.last

<template> 
<lightning-card title="CEO List">
        <div class="slds-m-around_medium">
            <template iterator:ceo={ceoList}>
                <ul key={ceo.value.id} class="slds-has-dividers_around-space">
                    <template if:true={ceo.first}>
                        <div class="slds-box slds-theme_shade">
                            <strong> List of Top compaies and Ceo Details</strong>
                        </div>
                    </template>
                    <li class="slds-item">
                        <Strong>{ceo.value.company}</Strong>                  
                        {ceo.value.name} {ceo.value.age} {ceo.value.salary}
                    </li>
                    <template if:true={ceo.last}>
                        <div class="slds-box slds-theme_shade">
                            <strong> Thank you</strong>
                        </div>
                    </template>
                    </ul>
            </template>
        </div>
    </lightning-card>
</template>

Javascript code
import { LightningElement } from 'lwc';

export default class Looping extends LightningElement {
    ceoList = [
        {id:1,name:'Sundar Pichai',age:49,salary:'2m',company:'Google'},
        {id:2,name:'Mark Zuckerberg',age:37,salary:'12B',company:'Meta'},
        {id:3,name:'Andy Jassy',age:54,salary:'35B',company:'Amazon'},
        {id:4,name:'Marc Benioff',age:57,salary:'26m',company:'salesfoce'},
        {id:5,name:'Joe Steier',age:58,salary:'500k',company:'SignatureHealthcare'},
    ]
}

Sunday 3 April 2022

Conditional Rendering in LWC?

 There are 2 special directive which is being used for conditional rendering of DOM element.
  1. if:true 
  2. if:false

 <template if:true={expression}>
    Render when expression is true
 </template>
 
  <template if:false={expression}>
    Render when expression is false
 </template>

Notes - 
1. Expression can be JavaScript property
2. Can be property of an object defined in JavaScript. example {employee.name}
3. Ternary operator can not be used inside expression.
4. Array also can not be used in the expression.
5. To use computed value use getters. 

Here is component code which have if-true if-false also computed expression in if-directive.
<template>
    <lightning-card title="Conditional Rendering">
        <div class="slds-m-around_medium">
            <lightning-button
            variant="brand"
            label="Show Data"
            title="Show Data"
            onclick={handleClick} class="slds-m-left_x-small">
            </lightning-button>
            <template if:true={isVisible}>
                <div >This is If-true directive example</div>
            </template>
            <template if:false={isVisible}>
                <div >This is If-false directive example,
                    Please click Button to see if-true content</div>
            </template>
            <lightning-input type="text" label="Enter Text" onkeyup={changeHandler}>

            </lightning-input>
            <template if:true={helloCheck}>
                <div>Congratulations you typed correctly. {typedValue}
                </div>
            </template>
        </div>
    </lightning-card>
</template>
Java script code
import { LightningElement } from 'lwc';

export default class HelloConditionalRendering extends LightningElement {
    isVisible = false;
    typedValue;
    handleClick(){
        this.isVisible = true;
    }
    changeHandler(event){
        this.typedValue = event.target.value;
    }
     get helloCheck(){
         return this.typedValue === "Hello";
     }
}