Sunday, September 26, 2021

Lightning Web Components Interview Questions- Part 4

 

31. How can we get Current Experience Builder Site

We can Import information about the current Experience Builder site from the @salesforce/community scoped module.

import propertyName from '@salesforce/community/property';
  • 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.
// demoSite.js
import { LightningElement } from 'lwc';
import Id from '@salesforce/community/Id';

export default class CommunityPage extends LightningElement {
   
}

32. 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.

<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
  <apiVersion>51.0</apiVersion>
  <isExposed>true</isExposed>
  <masterLabel>Demo Component</masterLabel>
  <description>This is a demo component from NewsTechnologyStuff.</description>
  <targets>
      <target>lightning__RecordPage</target>
      <target>lightning__AppPage</target>
      <target>lightning__HomePage</target>
  </targets>
  <targetConfigs>
      <targetConfig targets="lightning__RecordPage">
          <property name="prop1" type="String" />
          <objects>
              <object>Account</object>
              <object>Contact</object>
              <object>CustomObject__c</object>
          </objects>
      </targetConfig>
      <targetConfig targets="lightning__AppPage, lightning__HomePage">
          <property name="prop2" type="Boolean" />
      </targetConfig>
  </targetConfigs>
</LightningComponentBundle>

33. Share all the supported Target for LWC

Experience Builder

  • To make your component usable in Experience Builder, set isExposed to true. Then, in targets, add one of these values as a target:
    • lightningCommunity__Page  Create a drag-and-drop component that appears in the Components panel
    • lightningCommunity__Page_Layout to create a page layout component for LWR sites that appears in the Content Layout window
    • lightningCommunity__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 in targets and define the properties in targetConfigs. Only properties defined for the lightningCommunity__Page or lightningCommunity__Page_Layout targets are editable in Experience Builder.

Utility Bar:

<target>lightning__UtilityBar</target>

Outlook and Gmail

<target>lightning__Inbox</target>

How to use LWC in Flow

<target>lightning__FlowScreen</target>

Lightning web Components Document link

Lightning Web Components Interview Questions-Part 3

 

21. How to we can use Lightning Web Components outside Salesforce

You can check details here: Use Lightning Web Components in External WebSite Lightning out

22. Is it possible to iterate map in Lightning Web Components

We don’t have native OOTB support here, but we can iterate map in Lightning web components. You can check details here: Iterate Map in Lightning web components LWC

23. How to iterate sObject list in Lightning Web Components

We don’t have native OOTB support here, but we can iterate sObject list in Lightning web components. You can check details here: Display generic sObject in Lightning Web Components

24. How to access labels in Lightning web components

import labelName from '@salesforce/label/labelReference';

25. What is the Lightning Message Service

You can check details here: Lightning Message Service (LMS)

26. How to access events in Lightning Web Components

You can check details here: pas data between components using Events in Lightning Web Components

27. Where you can use/access Lightning Web components in Salesforce

We can use LWC in Flow, Lightning App Builder, Lightning Community, Utility Bar, Stand Alone Aura App, Custom tab and Visualforce, Salesforce Flow.

28. Explain Flow of lightning Web Components (LWC)

Flow of Lightning web components, Interview questions of LWC

28. Explain Styling Hooks for Lightning Web Components

Styling hooks provide a way for us to customize the default appearance of our LWC-based Base Components in a supported, maintainable, and intuitive way. You can check step by step guide here.

29. What is Aura Tokens?

Design Tokens 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 system for UI development.

To create a tokens bundle:

  1. In the Developer Console, select File | New | Lightning Tokens.
  2. Enter a name for the tokens bundle. The first tokens bundle should be named defaultTokens. The tokens defined within defaultTokens are automatically accessible in your Lightning components. Tokens defined in any other bundle won’t be accessible in your components unless you import them into the defaultTokens bundle.
<aura:tokens> 
    <aura:token name="myBodyTextFontFace" 
               value="'Salesforce Sans', Helvetica, Arial, sans-serif"/>
    <aura:token name="myBodyTextFontWeight" value="normal"/>
    <aura:token name="myBackgroundColor" value="#f4f6f9"/>
    <aura:token name="myDefaultMargin" value="6px"/>
</aura:tokens>

30. How you can use Aura Tokens and SLDS Design Token in LWC

To use custom Aura Tokens in LWC we need to follow below format:

// myLightningWebComponent.css
color: var(--c-myBackgroundColor);

LWC can use any Lightning Design System design token marked with Global Access. You can check the list here:

/* myLightningWebComponent.css */
div {
    margin-right: var(--lwc-spacingSmall);
}                                                                                                                                                                                                    

Lightning Web Components Interview Questions- Part 2

 

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.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 methods from the platformResourceLoader module.
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 }

we have few more methods available here:

loadScript(this, resourceName + '/lib.js')
    .then(() => { /* callback */ }); // Without CSS

Load multiple files:

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

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.

19. How to call Apex in Lightning Web Components

You can check details here: Call Apex method from Lightning Web Components

20. How we can use Lightning Web Components in Visualforce

You can check details here: Use Lightning Web Components in Visualforce

Lightning Web Components Interview Questions -Part 1

  We will share questions related to Lightning Web Components Interview Questions.

These questions are basic and medium level questions and will be helpful for everyone.

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.

Basic Sturcture of Lightning Web 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.

similarity between Aura and Lightning Web Compoents, Interview questions of LWC

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.

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, get property(){}. 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.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.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 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>

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>

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.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.

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.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- Part 2