1 What are Lightning Web Components (LWC)?
We can build Lightning components using two programming models: Lightning Web Components, and the original model, Aura Components. Lightning web components are custom HTML elements built using HTML and modern JavaScript. Lightning web components and Aura components can coexist and interoperate on a page. To admins and end users, they both appear as Lightning components.
Lightning Web Components uses core Web Components standards and provides only what’s necessary to perform well in browsers supported by Salesforce. Because it’s built on code that runs natively in browsers, Lightning Web Components is lightweight and delivers exceptional performance. Most of the code we write is standard JavaScript and HTML.
2 What is the file structure of Lightning Web Components
myComponent folder
myComponent.html
myComponent.js
myComponent.js-meta.xml
myComponent.css
myComponent.svg
The folder and its files must follow these naming rules.
- Can’t contain a hyphen (dash)
- Must begin with a lowercase letter
- Can’t include whitespace
- contain only alphanumeric or underscore characters
- Can’t end with an underscore
- Must be unique in the namespace
- Can’t contain two consecutive underscores
3. How can you display components HTML conditionally
To render HTML conditionally, add the if:true|false
directive to a nested <template> tag that encloses the conditional content.
Lightning Web Components Interview Questions 2021
4 How we can bind data in LWC
In the template, surround the property with curly braces, {
property}
. To compute a value for the property, use a JavaScript getter in the JavaScript class, getproperty(){}. In the template, the property can be a JavaScript identifier (for example, person
) or dot notation that accesses
a property from an object (person
.firstName
). LWC doesn’t allow computed expressions like person
[2].name
[‘John’].<!– hello.html –><template>Hello, {greeting}!</template>// hello.jsimport { LightningElement } from ‘lwc’;export default class Hello extends LightningElement {greeting = ‘World’;}<!– hello.html –> <template> Hello, {greeting}! </template> // hello.js import { LightningElement } from ‘lwc’; export default class Hello extends LightningElement { greeting = ‘World’; }
<!-- hello.html --> <template> Hello, {greeting}! </template> // hello.js import { LightningElement } from 'lwc'; export default class Hello extends LightningElement { greeting = 'World'; }
Don’t add spaces around the property, for example, { data }
is not valid HTML.
5. How we can pass data from HTML to JS controller?
We can use the onchange
attribute to listen for a change to its value. When the value changes, the handleChange
function in the JavaScript file executes.
Notice that to bind the handleChange
function to the template, we use the same syntax,
{handleChange}
<!– helloBinding.html –><template><p>Hello, {greeting}!</p><lightning-input label=”Name” value={greeting} onchange={handleChange}></lightning-input></template>// helloBinding.jsimport { LightningElement } from ‘lwc’;export default class HelloBinding extends LightningElement {greeting = ‘World’;handleChange(event) {this.greeting = event.target.value;}}<!– helloBinding.html –> <template> <p>Hello, {greeting}!</p> <lightning-input label=”Name” value={greeting} onchange={handleChange}></lightning-input> </template> // helloBinding.js import { LightningElement } from ‘lwc’; export default class HelloBinding extends LightningElement { greeting = ‘World’; handleChange(event) { this.greeting = event.target.value; } }
<!-- helloBinding.html --> <template> <p>Hello, {greeting}!</p> <lightning-input label="Name" value={greeting} onchange={handleChange}>
</lightning-input> </template> // helloBinding.js import { LightningElement } from 'lwc'; export default class HelloBinding extends LightningElement { greeting = 'World'; handleChange(event) { this.greeting = event.target.value; } }
We can use same eventHandler with multiple fields as well.<lightning-input name=’firstName’ label=”First Name” onchange={handleChange}></lightning-input><lightning-input name=’lastName’ label=”Last Name” onchange={handleChange}></lightning-input>In ControllerhandleChange(event) {const field = event.target.name;if (field === ‘firstName’) {this.firstName = event.target.value;} else if (field === ‘lastName’) {this.lastName = event.target.value;}}<lightning-input name=’firstName’ label=”First Name” onchange={handleChange}></lightning-input> <lightning-input name=’lastName’ label=”Last Name” onchange={handleChange}></lightning-input> In Controller handleChange(event) { const field = event.target.name; if (field === ‘firstName’) { this.firstName = event.target.value; } else if (field === ‘lastName’) { this.lastName = event.target.value; } }
<lightning-input name='firstName' label="First Name" onchange={handleChange}>
</lightning-input> <lightning-input name='lastName' label="Last Name" onchange={handleChange}>
</lightning-input> In Controller handleChange(event) { const field = event.target.name; if (field === 'firstName') { this.firstName = event.target.value; } else if (field === 'lastName') { this.lastName = event.target.value; } }
6. How we can iterate list in Lightning Web Component (LWC)
We have two options available here:
for:each
When using the for:each
directive, use for:item="
currentItem"
to access the current item. This example doesn’t use it, but to access the current item’s index, use for:index="
index"
.
To assign a key to the first element in the nested template, use the key={
uniqueId}
directive.<template for:each={contacts} for:item=”contact”> //where contacts is an array<li key={contact.Id}>{contact.Name}, {contact.Title}</li></template><template for:each={contacts} for:item=”contact”> //where contacts is an array <li key={contact.Id}> {contact.Name}, {contact.Title} </li> </template>
<template for:each={contacts} for:item="contact"> //where contacts is an array <li key={contact.Id}> {contact.Name}, {contact.Title} </li> </template>
Iterator
To apply a special behavior to the first or last item in a list, use the iterator directive, iterator:iteratorName={array}. Use the iterator directive on a template tag.
Use iteratorName to access these properties:
- value—The value of the item in the list. Use this property to access the properties of the array. For example, iteratorName.value.propertyName.
- index—The index of the item in the list.
- first—A boolean value indicating whether this item is the first item in the list.
- last—A boolean value indicating whether this item is the last item in the list.
<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><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>
<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>
7. Can we display multiple templates
Yes we can, We can import multiple HTML templates and write business logic that renders them conditionally. This pattern is similar to the code splitting used in some JavaScript frameworks.
Create multiple HTML files in the component bundle. Import them all and add a condition in the render() method to return the correct template depending on the component’s state. The returned value from the render() method must be a template reference,
which is the imported default export from an HTML file.// MultipleTemplates.jsimport { LightningElement } from ‘lwc’;import templateOne from ‘./templateOne.html’;import templateTwo from ‘./templateTwo.html’;export default class MultipleTemplates extends LightningElement {templateOne = true;render() {return this.templateOne ? templateOne : templateTwo;}switchTemplate(){this.templateOne = this.templateOne === true ? false : true;}}Component File structuremyComponent├──myComponent.html├──myComponent.js├──myComponent.js-meta.xml├──myComponent.css├──secondTemplate.html└──secondTemplate.css// MultipleTemplates.js import { LightningElement } from ‘lwc’; import templateOne from ‘./templateOne.html’; import templateTwo from ‘./templateTwo.html’; export default class MultipleTemplates extends LightningElement { templateOne = true; render() { return this.templateOne ? templateOne : templateTwo; } switchTemplate(){ this.templateOne = this.templateOne === true ? false : true; } } Component File structure myComponent ├──myComponent.html ├──myComponent.js ├──myComponent.js-meta.xml ├──myComponent.css ├──secondTemplate.html └──secondTemplate.css
// MultipleTemplates.js import { LightningElement } from 'lwc'; import templateOne from './templateOne.html'; import templateTwo from './templateTwo.html'; export default class MultipleTemplates extends LightningElement { templateOne = true; render() { return this.templateOne ? templateOne : templateTwo; } switchTemplate(){ this.templateOne = this.templateOne === true ? false : true; } } Component File structure myComponent ├──myComponent.html ├──myComponent.js ├──myComponent.js-meta.xml ├──myComponent.css ├──secondTemplate.html └──secondTemplate.css
8. What are the public properties in Lightning Web Component
Public properties are reactive. If the value of a public property changes, the component rerenders. To expose a public property, decorate a field with @api
. Public properties define the API for a component.
Lightning Web Components Interview Questions 2021
9. How to set Property from Parent component to child component
To communicate down the containment hierarchy, an owner can set a property on a child component. An attribute in HTML turns into a property assignment in JavaScript.// todoItem.jsimport { LightningElement, api } from ‘lwc’;export default class TodoItem extends LightningElement {@api itemName;}<c-todo-item item-name=”Milk”></c-todo-item><c-todo-item item-name=”Bread”></c-todo-item>// todoItem.js import { LightningElement, api } from ‘lwc’; export default class TodoItem extends LightningElement { @api itemName; } <c-todo-item item-name=”Milk”></c-todo-item> <c-todo-item item-name=”Bread”></c-todo-item>
// todoItem.js import { LightningElement, api } from 'lwc'; export default class TodoItem extends LightningElement { @api itemName; } <c-todo-item item-name="Milk"></c-todo-item> <c-todo-item item-name="Bread"></c-todo-item>
10. How we can pass data from parent component to child component
LWC support one way data transfer from parent to child. A non-primitive value (like an object or array) passed to a component is read-only. So the component cannot change the content of the object or array. As a result if the component tries to change the content, we will get errors in console.
We can pass primitive data types as most of the components supports this.
Lightning Web Components Interview Questions
11. How we can access elements in controller
We have two methods available here:
this.template.querySelector();
this.template.querySelectorAll();
Eg:<!– example.html –><template><div>First <slot name=”task1″>Task 1</slot></div><div>Second <slot name=”task2″>Task 2</slot></div></template>// example.jsimport { LightningElement } from ‘lwc’;export default class Example extends LightningElement {renderedCallback() {this.template.querySelector(‘div’); // <div>First</div>this.template.querySelector(‘span’); // nullthis.template.querySelectorAll(‘div’); // [<div>First</div>, <div>Second</div>]}}<!– example.html –> <template> <div>First <slot name=”task1″>Task 1</slot></div> <div>Second <slot name=”task2″>Task 2</slot></div> </template> // example.js import { LightningElement } from ‘lwc’; export default class Example extends LightningElement { renderedCallback() { this.template.querySelector(‘div’); // <div>First</div> this.template.querySelector(‘span’); // null this.template.querySelectorAll(‘div’); // [<div>First</div>, <div>Second</div>] } }
<!-- example.html --> <template> <div>First <slot name="task1">Task 1</slot></div> <div>Second <slot name="task2">Task 2</slot></div> </template> // example.js import { LightningElement } from 'lwc'; export default class Example extends LightningElement { renderedCallback() { this.template.querySelector('div'); // <div>First</div> this.template.querySelector('span'); // null this.template.querySelectorAll('div'); // [<div>First</div>,
<div>Second</div>] } }
12. What is the default value of Boolean property
False. We should give default value if we want to update value later.
13. How we can load third party JavaScript (JS) library in Lightning Web Components (LWC)
We have few ways here: using which we can load third party library:
- Import the static resource.
import resourceName from ‘@salesforce/resourceUrl/resourceName’;import resourceName from ‘@salesforce/resourceUrl/resourceName’;
import resourceName from '@salesforce/resourceUrl/resourceName';
- Import methods from the platformResourceLoader module.
import { loadStyle, loadScript } from ‘lightning/platformResourceLoader’;import { loadStyle, loadScript } from ‘lightning/platformResourceLoader’;
import { loadStyle, loadScript } from 'lightning/platformResourceLoader';
// libsD3.js/* global d3 */import { LightningElement } from ‘lwc’;import { ShowToastEvent } from ‘lightning/platformShowToastEvent’;import { loadScript, loadStyle } from ‘lightning/platformResourceLoader’;import D3 from ‘@salesforce/resourceUrl/d3’;import DATA from ‘./data’;export default class LibsD3 extends LightningElement {svgWidth = 400;svgHeight = 400;d3Initialized = false;renderedCallback() {if (this.d3Initialized) {return;}this.d3Initialized = true;Promise.all([loadScript(this, D3 + ‘/d3.v5.min.js’),loadStyle(this, D3 + ‘/style.css’)]).then(() => {this.initializeD3();}).catch(error => {this.dispatchEvent(new ShowToastEvent({title: ‘Error loading D3’,message: error.message,variant: ‘error’}));});}initializeD3() { //some code }// libsD3.js /* global d3 */ import { LightningElement } from ‘lwc’; import { ShowToastEvent } from ‘lightning/platformShowToastEvent’; import { loadScript, loadStyle } from ‘lightning/platformResourceLoader’; import D3 from ‘@salesforce/resourceUrl/d3’; import DATA from ‘./data’; export default class LibsD3 extends LightningElement { svgWidth = 400; svgHeight = 400; d3Initialized = false; renderedCallback() { if (this.d3Initialized) { return; } this.d3Initialized = true; Promise.all([ loadScript(this, D3 + ‘/d3.v5.min.js’), loadStyle(this, D3 + ‘/style.css’) ]) .then(() => { this.initializeD3(); }) .catch(error => { this.dispatchEvent( new ShowToastEvent({ title: ‘Error loading D3’, message: error.message, variant: ‘error’ }) ); }); } initializeD3() { //some code }
// libsD3.js /* global d3 */ import { LightningElement } from 'lwc'; import { ShowToastEvent } from 'lightning/platformShowToastEvent'; import { loadScript, loadStyle } from 'lightning/platformResourceLoader'; import D3 from '@salesforce/resourceUrl/d3'; import DATA from './data'; export default class LibsD3 extends LightningElement { svgWidth = 400; svgHeight = 400; d3Initialized = false; renderedCallback() { if (this.d3Initialized) { return; } this.d3Initialized = true; Promise.all([ loadScript(this, D3 + '/d3.v5.min.js'), loadStyle(this, D3 + '/style.css') ]) .then(() => { this.initializeD3(); }) .catch(error => { this.dispatchEvent( new ShowToastEvent({ title: 'Error loading D3', message: error.message, variant: 'error' }) ); }); } initializeD3() { //some code }
we have few more methods available here:
Load multiple files:Promise.all([loadScript(this, resourceName + ‘/lib1.js’),loadScript(this, resourceName + ‘/lib2.js’),loadScript(this, resourceName + ‘/lib3.js’)]).then(() => { /* callback */ });Promise.all([ loadScript(this, resourceName + ‘/lib1.js’), loadScript(this, resourceName + ‘/lib2.js’), loadScript(this, resourceName + ‘/lib3.js’) ]).then(() => { /* callback */ });
Promise.all([ loadScript(this, resourceName + '/lib1.js'), loadScript(this, resourceName + '/lib2.js'), loadScript(this, resourceName + '/lib3.js') ]).then(() => { /* callback */ });
14. Is it possible to call Third party API from LWC JS
By default, we can’t make WebSocket connections or calls to third-party APIs from JavaScript code.
To do so, add a remote site as a CSP Trusted Site.
The Lightning Component framework uses Content Security Policy (CSP), which is a W3C standard, to control the source of content that can be loaded on a page. As a result the default CSP policy doesn’t allow API calls from JavaScript code. So to change the policy, and the content of the CSP header, by adding CSP Trusted Sites.
15. How to access static resource
You can check details here: Use Static Resource in Lightning Web Components
16 How to get current User ID?
You can check details here: GetCurrent User Details in Lightning Web Components.
Lightning Web Components Interview Questions 2021
17. How we can make changes in components body after it rendered?
The renderedCallback()
is unique to Lightning Web Components. Use it to perform logic after a component has finished the rendering phase.
This hook flows from child to parent. A component is usually rendered many times during the lifespan of an application. To use this hook to perform a one-time operation, use a boolean field like hasRendered
to track whether renderedCallback() has been executed. So The first time renderedCallback() executes, perform the one-time operation and set hasRendered
=true. If hasRendered
=true, don’t perform the operation.
18. What are the decorators in LWC
@api
Public properties are reactive. If the value of a public property changes, the component rerenders. To expose a public property, decorate a field with @api. Public properties define the API for a component.
To expose a public method, decorate it with @api. Public methods are part of a component’s API. To communicate down the containment hierarchy, owner and parent components can call JavaScript methods on child components.
@track
Fields are reactive. If a field’s value changes, and the field is used in a template or in a getter of a property that’s used in a template, the component rerenders and displays the new value.
There is one use case for @track. When a field contains an object or an array, there’s a limit to the depth of changes that are tracked. To tell the framework to observe changes to the properties of an object or to the elements of an array, decorate the field with @track.
@wire
To read Salesforce data, Lightning web components use a reactive wire service. When the wire service provisions data, the component rerenders. Components use @wire in their JavaScript class to specify a wire adapter or an Apex method.
Lightning Web Components Interview Questions
19. How can we get Current Experience Builder Site
We can Import information about the current Experience Builder site from the @salesforce/community
scoped module.
property
—The supported properties are:Id
—The ID of the current site.basePath
—The base path is the section of the site’s URL that comes after the domain.- So if your site domain name is newstechnologystuff.force.com and lwcdemo was the URL
- value added when you created the site, the community’s URL is newstechnologystuff.force.com/lwcdemo/s. In this case, lwcdemo/s is the base path.
propertyName
—A name that refers to the imported Experience Builder property.
20. How we can access LWC in Lightning App Builder
We need to use Targets to define where we want to use LWC components. Below sample support for the Record page and the Home and App Page. Also set isExposed to true. We can also provide
different properties on a different screens.
21. Share all the supported Target for LWC
Experience Builder
- To make your component usable in Experience Builder, set
isExposed
totrue
. Then, intargets
, add one of these values as atarget
:lightningCommunity__Page
Create a drag-and-drop component that appears in the Components panellightningCommunity__Page_Layout
to create a page layout component for LWR sites that appears in the Content Layout windowlightningCommunity__Theme_Layout
This will create a theme layout component for LWR sites that appears in Settings in the Theme area
- To include properties that are editable when the component is selected in Experience Builder, define
lightningCommunity__Default
intargets
and define the properties intargetConfigs
. - Only properties defined for the
lightningCommunity__Page
orlightningCommunity__Page_Layout
targets are editable in Experience Builder.
Lightning Web Components Interview Questions 2021
22.How to call a controller method in javascript?
var action=component.get(“methodname”)
23.What is the use of do init method?
It will be loaded on loading of lightning applicationIt is pretty much similar to constructor.
24.What is the use of attribute?
Attribute is like a variable. If you want to store the datathen we should go with attribute.
25.What is bounded expression?
We will able to get the new value. syntax: {!v.attribute name}
26.What is unbounded expression?
we will not able to get the new value. syntax:{#v.attributename}
27.What is the use of AuraEnabled annotation?
if you want to access the data in the lightning applicationthen we should write AuraEnabled
annotation->we will not able to access the data in lightning application without auraEnabled
28.What is the use of global action in the controller?
$A.enqueueAction(action)It’s used to execute the server side logic
29.Can we write void method in lightning?
No
30.How to get the response from callback?
reponse.getReturnValue()
31.How to get the state in controller?
response.getState()
32.Why helper method is a best practice in lightning?
It’s used for re usability.
33.What is reusability in lightning?
We will able to access the value from one method to other method.
method1:function(component){var name=’sfdcscenarios’;this.method2(name);},method2:function(name){//reusabilityconsole.log(‘name from method1 is’+name);}function(component){var name=’sfdcscenarios’;this.method2(name); }, method2: function(name){//reusabilityconsole.log(‘name from method1 is’+name);}
function(component){var name=’sfdcscenarios’;this.method2(name); }, method2: function(name){//reusabilityconsole.log(‘name from method1 is’+name);}
34.Does it happens in the controller?
No. It will happens in the helper.
35.what framework lightning will follow?
aura framework.
36.How many tags we have in lightning?
ui tagsLightning tags.
37.What is exends=”force:slds”?
It will acquire the properties of lightning design system?
38.What happens if you don’t put exends=”force:slds” in lightning application?
It will look like normal html file.
39.What is v in attribute?
It’s a value provider. If you want to access the value from the attribute then we willuse
{!v.attrname} or{#v.attributename}
40.When we should go with unbounded expression?
If you are simply dealing with read operation then we should go withunbounded expression
41. Does reusability is possible in controller?
No
42.What is Lightning component bundle?
component controller helper design svg Documentation style renderer.
43.What is renderer?
If you want to override the standard rendering mechanism in salesforce lightningthen
we should go with renderer.
44.What are the events in salesforce lightning?
1.component event
2.application event
3. system events
45.Which interface should you use if you want to get the id of the record from the record
Detail page?
force:hasRecordId
46. Can we call one component to another component?
Yes,we can call.
47.How to call lightning component in visual force page?
<aura:application access=”GLOBAL” extends=”ltng:outApp”><aura:dependency resource=”c:FlipCard”/></aura:application>*Add the <apex:includeLightning /> component to your Visualforce page.*Reference a Lightning app that declares your component dependencies with $Lightning.use().*Write a function that creates the component on the Visualforce page with $Lightning.createComponent().<aura:application access=”GLOBAL” extends=”ltng:outApp”> <aura:dependency resource=”c:FlipCard”/> </aura:application> *Add the <apex:includeLightning /> component to your Visualforce page. *Reference a Lightning app that declares your component dependencies with $Lightning.use(). *Write a function that creates the component on the Visualforce page with $Lightning.createComponent().
<aura:application access=”GLOBAL” extends=”ltng:outApp”> <aura:dependency resource=”c:FlipCard”/> </aura:application> *Add the <apex:includeLightning /> component to your Visualforce page. *Reference a Lightning app that declares your
component dependencies with $Lightning.use(). *Write a function that creates the component on
the Visualforce page with $Lightning.createComponent().
48.How to pass the parameters in controller?
action.setParams
49.How to Navigate From One Lightning Component to Another Lightning Component?
“e.force:navigateToComponent”
50. How to go from one lightning page to another lightning page through a click?
var urlEvent = $A.get(“e.force:navigateToURL”);
No comments:
Post a Comment