Sunday, December 22, 2019

Salesforce Lightning Web Components Interview Questions

1) What is LWC(Lightning Web Components)?

As of now, we have built a lightning component using the "Aura Components model". we can also build a lightning component using the "Lightning Web Components model". Lightning Web Components are custom HTML elements build using the HTML Elements and modern Javascript. We can build components using any of the models and can place these components on the same lightning page.

For developing LWC we require  "Salesforce Extensions for Visual Studio Code" and for deploying LWC from an org we require "Salesforce CLI".

Aura Components make use of own custom component model, custom templates, custom components, etc while LWC is built on web standards and it makes use of web components, templates, custom elements which we have in web standards. Both the Aura component, LWC make use of Security, LDS and Base lightning components.

Important points to note:

1) Aura component and LWC can exist on the same lightning page.
2) Aura component can include LWC


2) What is Scratch org?

Scratch org is a disposable Salesforce org used for development and testing.
Scratch org can be created for a maximum of 30 days after which scratch org gets deactivated. The default duration for Scratch org is 7 days.


3) Explain the Lightning Web Component Bundle?

LWC bundle contains an HTML file, a JavaScript file, and a metadata configuration file
and these files are created once we create a Lightning web component.

We can also create a .css file for styling purpose and We can also create SVG file for the purpose of displaying icon.


4) How to render the HTML file conditionally?

If we want to render HTML conditionally we can make use of if:true={propertyName},if:false={propertyName} in nested template tag.


5) How to iterate over an array in HTML file?

We can make use of for:each directive and iterator directive.

for:each directive:

for:each directive is used to render an array. To render an array add the for:each directive to a nested template tag, for:item is used to access the current item, for:index is used to access the current index.


Iterator directive:



If you have the requirement to access the first and the last element in the list use the iterator directive.

A sample HTML file is as shown below.

.html file

<template>
    <!--for:each-->
    <b>for:each directive</b>
    <template for:each={students} for:item="item" for:index="index">
        <p key={item.id}>
            {item.Name}
            {item.Branch}
        </p>
    </template>
    <!--Iterator directive-->
    <b>Iterator directive</b>
    <template iterator:it={students}>
<li key={it.value.id}>
{it.value.id}
{it.value.Name}
{it.value.Branch}
</li>
<!--To access the first and the last element use {it.first} and {it.last}-->
    </template>
   
</template>


6) What are the types of decorators in lightning web components?

We have 3 Decorators in Lightning Web Components.

1) @api
2) @track
3) @wire


7) Explain all three decorators in lightning web components?

Refer to the below link for an explanation.



How we can build Lightning web components?

It is always recommended to use Salesforce DX tools for developing Lightning web components however we can still use code editor to develop Lightning web components. 

Note: we cannot build LWC in the Developer Console.


9) How can we use Lightning web component with unsupported tool?

To use a Lightning web component with an unsupported experience or tool we can wrap it in an Aura component.


10) Which command is use to authorize a dev hub?

"SFDX: Authorize a Dev Hub"


11) How many scratch orgs we can create daily, and how many can be active at a given point?

Our "Dev Hub" org edition determines how many scratch orgs we can create daily, and how many can be active at a given point.


12) How many files are created by default when we create a Lightning Web Component?

Three files are created as below.

HTML file.
JavaScript file.
Meta configuration file.


13) What is the purpose of .css file and svg file in Lightning Web Component bundle?

 .css file is use for styling purpose and svg file is use for purpose of displaying icon.


14) What is the purpose of HTML file in Lightning Web Component bundle?

  1. The HTML file is enclosed within the <template> tags.
  2. It contains the component HTML.
Sample HTML file shown below,

<template>
    <h1> Some Text </h1>
</template>


15) What is the purpose of JavaScript file in Lightning Web Component bundle?


  1. The JavaScript file defines the behavior of HTML element present in HTML file.
  2. JavaScript files in Lightning web components are ES6 modules. By default, everything declared in a module is local—it’s scoped to the module.
  3. If we want to import a class, function, or variable declared in a module we use the import statement. 
  4. If we want to allow other code to use a class, function, or variable declared in a module we use the export statement.
  5. The core module in Lightning Web Components is lwc. The import statement imports LightningElement from the lwc module.



import { LightningElement } from 'lwc';

Here, LightningElement is a custom wrapper of the standard HTML element.



Extend LightningElement to create a JavaScript class for a Lightning web component. You can’t extend any other class to create a Lightning web component.



export default class MyComponent extends LightningElement {

    // Code

}



The JavaScript file can contain:



The component’s public API via public properties and methods annotated with @api.

Private properties

Event handlers


16) What is Meta configuration file in Lightning Web Component?

The Meta configuration file defines the metadata values for the components.

If we don’t include a configuration file for our component, we get an error shown below when we push your changes. 

"Cannot find Lightning Component Bundle <component_name>".


17) Is it possible to use multiple html files in a Lightning Web Component?

Yes and for this we will need to create multiple HTML files in the component bundle and than Import them all and add a condition in the render() method to return the correct template.


18) How many style sheet can a component have?

Each component can have only one style sheet.


19) Can components share the style sheet?

No.


20) Does the style of the component get lost or override when we use the component with its own style sheet in different context?

When we define a style sheet for a component in a component folder it is limited to that component only and this avoid loosing the style sheet of the component when we reuse this component in different contexts. This also avoid component style sheet getting override in other part of the page.


21) How to share CSS style sheet in Lightning Web Component?

1) If we want to share CSS style than we will need to create a module that contains only a CSS file and for this we will need to create a Lightning Web Component with only single CSS file as shown below.

How to share CSS style sheet in Lightning Web Component

2) After we create a module we can import the module into CSS file of any Lightning Web Component as shown below.

@import 'namespace/nameOfModule';

22) What is used to display toast notifications in Lightning Web Component?

Toast notification pops up to alert users of a success, error, or warning. 
We need to import ShowToastEvent from the lightning/platformShowToastEvent module to display a toast notification in Lightning Experience or Experience Builder sites.


23) List the callback methods that handles life cycle of LWC?

Lightning web components have callback methods that handle the lifecycle of LWC.

constructor()
connectedCallback()
disconnectedCallback()
render()
renderedCallback()
errorCallback(error, stack)

For more details visit --> Lifecycle hooks in LWC

24) Explain @track decorator in LWC with example?


25) Explain @api decorator in LWC with example?


26) Explain @wire decorator in LWC with example?



27) How to pass data from child component to parent component in lightning web component?


To pass data from child component to parent component we can trigger event from child LWC and handled it parent LWC as shown in below example.

childcompdemo.html


In the child component HTML file, we are firing event based on button click.


<template>
    <div>
        Hi, I am from child component HTML file.
        <lightning-button label="Click Me To Fire Event" onclick={handlebuttonclick}></lightning-button>
    </div>
</template>



childcompdemo.js


In the child comp js file, we are passing childcompname and childcompdescription property to parent component.

import { LightningElement, api } from 'lwc';

export default class Childcompdemo extends LightningElement {

    @api childcompname='Name of comp is childemocomp';
    @api childcompdescription='Description of comp is testing';
    handlebuttonclick(){
       const evt= new CustomEvent('myfirstevent', {detail:{childcompname:this.childcompname,childcompdescription:this.childcompdescription}});
       this.dispatchEvent(evt);
    }
}


parentcompdemo.html


In the parent component HTML file, we are handling the child comp event.

The keyword "on" is appended before the name of the event using which it is fired.

In this example, we have fired the event from the child component using the name "myfirstevent".

<template>
    <div>
        Hi, I am from parent component HTML file.
        <c-childcompdemo onmyfirstevent={handlechildevent}></c-childcompdemo>
    </div>
</template>



parentcompdemo.js


/* eslint-disable no-alert */
import { LightningElement } from 'lwc';

export default class Parentcompdemo extends LightningElement {

    handlechildevent(event){
      const childcompname=event.detail.childcompname;
      const childcompdescription=event.detail.childcompdescription;
      alert('Event handled in Parent Comp');
      alert('child comp name is:'+childcompname);
      alert('child comp description is:'+childcompdescription);
    }
}


lightningapp.app


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


How to pass data from child component to parent component in lightning web component

child to parent communication in lwc

child to parent communication in lwc

pass data from child to parent lwc


28) How to pass data from parent component to child component in lightning web component?

We can pass data from parent LWC to child LWC while calling the child LWC from parent LWC.

In child LWC we need to decorate properties with @api decorator as shown in below example.

Properties decorated with @api are public reactive properties. When we use the @api decorator, we must import it explicitly from lwc as shown below.

import { LightningElement, api } from 'lwc';

Parent component can make use of the Public Property.


childcompdemo.html



<template>
    <div>
        <p>
        Hi, I am from child component HTML file.
       </p>
        <p>
        <b>Message from parent comp is </b> : {messagefromparent}
       </p>
       <p>
        <b>Name of parent comp is </b>: {parentcompname}
       </p>
    </div>
</template>      


childcompdemo.js



import { LightningElement, api } from 'lwc';

export default class Childcompdemo extends LightningElement {

    @api messagefromparent;
    @api parentcompname;

}


parentcompdemo.html




<template>
    <div>
        Hi, I am from parent component HTML file.
        <c-childcompdemo messagefromparent="Hi this message is from parent comp" parentcompname="parentcompdemo" ></c-childcompdemo>
    </div>
</template>



parentcompdemo.js



//* eslint-disable no-alert */
import { LightningElement } from 'lwc';

export default class Parentcompdemo extends LightningElement {

}

lightningapp.app



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



How to pass data from parent component to child component in lightning web component

29) How to call child component method from parent component in lightning web component?

We will call child component method from parent component in using querySelector.

childDemoComp.html

<template>
    <div>
        <p>
        Hi, I am from child component HTML file.
       </p>
        <p>
        <b>Message from parent comp is </b> : {messagefromparent}
       </p>
       <p>
        <b>Name of parent comp is </b>: {parentcompname}
       </p>
    </div>
</template>      


childDemoComp.js

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

export default class childDemoComp extends LightningElement {

    @track messagefromparent;
    @track parentcompname;

    @api childMethod(){
        this.messagefromparent='ParentCompMsg';
        this.parentcompname='ParentCompName';
    }
}


parentDemoComp.html

<template>
    <div>
        Hi, I am from parent component HTML file.
        <lightning-button variant="brand" label="CallChildCompMethod" onclick={handleButtonClick}>
        </lightning-button>
        <c-child-demo-comp></c-child-demo-comp>
    </div>
</template>


parentDemoComp.js

//* eslint-disable no-alert */
import { LightningElement } from 'lwc';

export default class parentDemoComp extends LightningElement {
  handleButtonClick(){
    this.template.querySelector("c-child-demo-comp").childMethod();
  }
}


testApp.app


<aura:application>
<c:parentDemoComp></c:parentDemoComp>
</aura:application>    



How to call child component method from parent component in lightning web component


How to call child component method from parent component in lightning web component

30) Can AURA component exist as a parent component to LWC?

--> Yes

31) How to pass value from child LWC to parent AURA comp?

We can trigger event from child LWC comp and handled in parent AURA comp 
as shown in below example.


32) How to call method of child LWC from parent Aura component?

To call method of child LWC from parent Aura component we will need to decorate the

child LWC method with @api decorator, In AURA component we need to first assign aura id to child

LWC as highlighted in yellow color. Using component.find() we can get the child LWC and

 finally call its method as highlighted in AURA component JS file.

parentAuraComp.cmp


<aura:component>

<div>

    I am parent Aura Component.

</div>

<c:childLwcComp aura:id="childLwcCompId"></c:childLwcComp>

<lightning:button label="Call Child LWC Comp" variant="brand" onclick="{!c.callChildMethod}" ></lightning:button>

</aura:component>         

 


parentAuraCompController.js


({

 

    callChildMethod : function(component, event, helper) {

        var findChildComp=component.find('childLwcCompId');

        findChildComp.lwcCompMethodDescription('Hi I am Aura Component Message');

      }

})


childLwcComp.html


<template>

    <div>

        I am child LWC component.

    </div>

</template>


childLwcComp.js


import { LightningElement,api } from 'lwc';

 

export default class ChildLwcComp extends LightningElement {

    

    @api

    lwcCompMethodDescription(messageFromAura){

        alert('messageFromAura :'+ messageFromAura);

        

    }

 

}



auraAppForTesting.app


<aura:application>

<c:parentAuraComp></c:parentAuraComp>

</aura:application>          


Output:


How to call lwc method from Aura component

    How to call lwc method from Aura component

33) How to get record id in lightning web component?

By using force:hasRecordId interface in Aura component we can get the id of the current record however in LWC it is very easy to get the id of the current record.

In the component’s JavaScript class, we use @api decorator to create a public recordId property.


For more details visit --> How to get record id in lightning web component?


34) How to pass parameter from LWC to apex controller and how to handle
apex response in LWC JS controller?

You can give this example to explain how we can pass parameter from LWC to apex controller and how to handle apex response in LWC JS controller.



35) How to call an apex method imperatively in LWC?

If we want to control when the method invocation should occurs (for example, in response to clicking a button) than we call the method imperatively. 

When we call a method imperatively, we receive only a single response. 

However with @wire, it delegates control to the framework and results in a stream of values being provisioned.

Let us understand with a simple example,


getAccountDataImperatively.html

<template>

    <div >

 

        <lightning-input type="text" label="Enter Account Name" value={accName} onchange={handleChange}> </lightning-input>

        <lightning-button variant="base" label="Search Account" title="Search Account" onclick={handleChangeMethod} class="slds-m-left_x-small"></lightning-button>

        <p>Displaying Account Information</p>

 

        <template if:true={accountRecord}>

 

            <template for:each={accountRecord} for:item="item" for:index="index">

 

                <p key={item.Id}>

 

                   Name: {item.Name}

 

                </p>

 

            </template>

 

        </template>

 

        <template if:true={error}>

 

            Some error occured.

 

        </template>

 

    </div>

</template>


getAccountDataImperatively.js

import { LightningElement,track } from 'lwc';

import getAccountRecordMethod from '@salesforce/apex/customAccountController.getAccountRecordMethod';

export default class GetAccountDataImperatively extends LightningElement {

    @track accountRecord;

    @track error;

    @track accName;

 

    handleChange(event){

 

        const userInput = event.target.value;

 

        this.accName= userInput;

 

    }

 

    handleChangeMethod() {

        getAccountRecordMethod({

            accNameParamInApex : this.accName

        })

            .then(result => {

                this.accountRecord = result;

            })

            .catch(error => {

                this.error = error;

            });

    }

   

}




getAccountDataImperatively.js-meta.xml

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

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

    <apiVersion>50.0</apiVersion>

    <isExposed>false</isExposed>

</LightningComponentBundle>


customAccountController.cls

public with sharing class customAccountController {

    public customAccountController() {

 

    }

    @AuraEnabled(cacheable=true)

    public static List<Account> getAccountRecordMethod(String accNameParamInApex) {

 

        String accNameKey = '%'+accNameParamInApex+'%';

 

    List<Account> accList=[SELECT Id, Name, Industry

 

        FROM Account

 

        Where name Like: accNameKey];

 

        return accList;

 

    }

}


testingLWCCompApp.app

<aura:application>

<c:getAccountDataImperatively></c:getAccountDataImperatively>

</aura:application>       


Output:

How to call an apex method imperatively in lwc



36) What all operation we can perform using lightning/uiRecordApi?


Using lightning/uiRecordApi we can perform operations as mentioned below without using Apex.

1) Create a record 

2) Get record data

3) Delete a record

4) Get a field value from record

5) Update a record and etc.


37) How to get information related to an object in LWC?

we can make use of getObjectInfo  to get information related to an object

such as fields, apiName etc. 

For example please refer: How to use getObjectInfo in Lightning Web Component?


TAGS:

#lwc interview questions#lightning web components interview questions#salesforce lwc interview questions#salesforce lightning web components interview questions#lwc salesforce interview questions#interview questions on lwc#interview questions on lwc salesforce#lightning web components interview questions and answers#interview questions on lightning web components
#lwc interview questions in salesforce#lwc interview questions salesforce#lwc interview questions and answers

4 comments:

  1. Really Appreciable!
    You have shared very valuable information that people should recognise. Thank you for sharing such an informative post with us. I would like share my contribution, sharing with you all my Salesforce app specially for Salesforce admins and developers and saves their most of time in performing bulk operations such as Bulk object/field creation, updation, deletion, cloning, etc., which is also available on appexchange:
    Bulk Object Field Creator
    Appexchange Url

    ReplyDelete
  2. Thanks you so much,more information

    ReplyDelete
  3. Thaanks for youl r valuable information.... really helpful

    ReplyDelete
  4. Very nice contained. I hope I get a job by reading this soon.

    ReplyDelete