50 LWC Lightning Web Component Interview Questions

50 LWC Lightning Web Component Interview Questions

On May 21, 2024, Posted by , In Interview Questions, With Comments Off on 50 LWC Lightning Web Component Interview Questions

50 Scenario based exclusive Salesforce Lightning Interview Questions with detailed Answers by CRS info Solutions with code snippets and unique answers.

Salesforce Lightning interview questions and answers CRS info Solutions

Table of Contents

1. What are the type of events into Salesforce Lightning component?

  • Application Event(Salesforce Document)
  • Component Event
  • System Event(Salesforce Document)

Application Event

Application events are used to communicate across the application. These events are typically used when you need to notify multiple components or when the event needs to be handled by any component in the application, regardless of its location in the component hierarchy.

Usage: These events are declared in the aura:event tag with the type="APPLICATION" attribute.
Example: An application event to notify all components of a data update.

<!-- appEvent.evt -->
<aura:event type="APPLICATION">
    <aura:attribute name="message" type="String"/>
</aura:event>

Component Event

Component events are used to communicate between a parent and child component. These events are handled by the parent component and are typically used for interactions between components that are directly related.

Usage: These events are declared in the aura:event tag with the type="COMPONENT" attribute.
Example: A component event to notify a parent component of a button click.

<!-- cmpEvent.evt -->
<aura:event type="COMPONENT">
    <aura:attribute name="message" type="String"/>
</aura:event>

System Event

System events are predefined events in the Lightning framework that are used to handle specific system activities like component rendering, initialization, destruction, etc. These events are not defined by the user but are part of the Lightning framework.

Usage: These events are typically handled in the JavaScript controller using event handlers such as init , render , afterRender , rerender , unrender , etc.
Example: Handling the init event to perform actions when a component is initialized.

({
    doInit : function(component, event, helper) {
        // handle component initialization
    }
})

2. What is the basic difference between Application Event and Component Event?

The major difference between application and component event is that component event is used in child to parent components and application event can be used throughout the application.

Application EventComponent Event
Application-wide communicationComponent hierarchy (parent-child communication)
Used when multiple components need to respondUsed for direct communication between related components
Any component in the application can handle it.Handled by parent or another component in the containment hierarchy
aura:event with type="APPLICATION" aura:event with type="COMPONENT"
Broadcasting updates or actions to many componentsInteracting between a parent component and its children

3. Which interface needs to be implemented so that you can use lightning components as quick action?

To use Lightning components as quick actions, you need to implement the force:lightningQuickAction interface.

Here is an example of how to implement this interface in a Lightning component:

<aura:component implements="force:lightningQuickAction,force:hasRecordId" access="global">
    <aura:attribute name="recordId" type="String" />
    <!-- Your component's content goes here -->
</aura:component>

In this example:

  • force:lightningQuickAction allows the component to be used as a quick action.
  • force:hasRecordId provides access to the record ID of the context where the quick action is invoked, which is often necessary for the component’s functionality.

4. Which interface needs to be implemented so that you can use the lightning component as Tab like custom object and VF page?

To use a Lightning component as a custom tab, like a custom object or Visualforce page, you need to implement the force:appHostable interface.

Here is an example of how to implement this interface in a Lightning component:

<aura:component implements="force:appHostable" access="global">
    <!-- Your component's content goes here -->
</aura:component>

By implementing the force:appHostable interface, the Lightning component can be used as a custom tab in Salesforce, similar to custom objects and Visualforce pages.

5. Can we use Lightning Components in the VF page?

Yes, you can use Lightning components in a Visualforce page by using the <lightning:container> tag. This allows you to embed Lightning components within Visualforce pages, enabling you to leverage the capabilities of Lightning components in the context of Visualforce.

Here is an example of how to embed a Lightning component in a Visualforce page:

Lightning Component (exampleComponent.cmp)

<aura:component>
    <aura:attribute name="message" type="String" default="Hello from Lightning Component!" />
    <div>{!v.message}</div>
</aura:component>

Visualforce Page

<script>
    function handleError(error) {
        console.log('Error: ' + error);
    }
    function handleLoad() {
        console.log('Lightning component loaded successfully');
    }
</script>

In this example:

  • The lightning:container tag is used to embed the exampleComponent Lightning component within the Visualforce page.
  • The componentDef attribute specifies the name of the Lightning component to be embedded.
  • Optional onerror and onload event handlers can be used to manage errors and handle successful loading of the Lightning component.

This integration allows you to bring the rich functionality of Lightning components into the Visualforce environment.

6. How can we call the child component controller method from the parent component controller method?

To call a child component’s controller method from a parent component’s controller method in Salesforce Lightning, you can use Aura’s component reference and method invocation features. Here is a step-by-step example:

Step 1: Define a Method in the Child Component’s Controller

Child Component (childComponent.cmp)

({
    childMethod: function(component, event, helper) {
        var param = event.getParam("param");
        console.log("Child method called with parameter: " + param);
    }
})

Child Component Controller (childComponentController.js)

<aura:component>
    <c:childComponent aura:id="childCmp" />
    <lightning:button label="Call Child Method" onclick="{!c.callChildMethod}" />
</aura:component>

Step 2: Reference the Child Component in the Parent Component

Parent Component (parentComponent.cmp)

({
    callChildMethod: function(component, event, helper) {
        var childCmp = component.find("childCmp");
        childCmp.childMethod("Hello from Parent");
    }
})

Parent Component Controller (parentComponentController.js)

Explanation

  1. Child Component Definition:
    • The aura:method tag in the child component defines a public method named childMethod with a parameter param.
    • The childMethod function in the child component’s controller logs the received parameter.
  2. Parent Component Definition:
    • The parent component includes the child component using the <c:childComponent> tag and assigns it an auraof "childCmp".
    • A button is added to the parent component to trigger the callChildMethod function in the parent component’s controller.
  3. Parent Component Controller:
    • The callChildMethod function in the parent component’s controller finds the child component using component.find("childCmp").
    • It then calls the childMethod function defined in the child component with a parameter.

7. What are the different Lightning component bundles?

In Salesforce Lightning, a Lightning component bundle includes several resources that define the component’s behavior, appearance, and functionality. Here are the different parts of a Lightning component bundle:

  1. Component (.cmp): The main markup file that defines the structure and layout of the component.
  2. Controller (.js): The client-side JavaScript controller that handles events and user interactions.
  3. Helper (.js): A JavaScript file that contains reusable functions to support the controller’s logic.
  4. Style (.css): The CSS file that defines the component’s styling and appearance.
  5. Renderer (.js): A JavaScript file that overrides the default rendering behavior of the component.
  6. Design (.design): An XML file that defines the design-time behavior and properties of the component in Lightning App Builder.
  7. SVG (.svg): An SVG file that provides a custom icon for the component.
  8. Documentation (.auradoc): An XML file that contains the component’s documentation, including examples and descriptions.

Summary of Lightning Component Bundles

ResourceDescription
Component (.cmp)Defines the component’s structure and layout.
Controller (.js)Handles client-side events and interactions.
Helper (.js)Contains reusable JavaScript functions.
Style (.css)Defines the component’s styling and appearance.
Renderer (.js)Overrides the default rendering behavior of the component.
Design (.design)Defines design-time properties for use in Lightning App Builder.
SVG (.svg)Provides a custom icon for the component.
Documentation (.auradoc)Contains documentation and examples for the component.

Each of these resources plays a specific role in defining and enhancing the functionality, appearance, and usability of a Lightning component in Salesforce.

Salesforce lightning interview questions Set 1
Salesforce lightning interview questions Set 1

8. What is the use of Document and Renderer in lightning components?

In Salesforce Lightning components, the Document and Renderer files serve specific purposes that enhance the functionality and behavior of components.

Document (.auradoc)

The Document (.auradoc) file is used to provide documentation for a Lightning component. It helps developers understand how to use the component, its attributes, events, and examples. This file is especially useful for internal teams or for sharing components with other developers.

<!-- ExampleComponent.auradoc -->
<aura:documentation>
    <aura:description>
        This component displays a greeting message.
    </aura:description>
    <aura:example name="Simple Example" ref="exampleComponentExample.cmp">
        An example showing the use of the component.
    </aura:example>
    <aura:attribute name="message" type="String" description="The message to be displayed." />
</aura:documentation>

Renderer (.js)

The Renderer (.js) file allows you to override the default rendering behavior of a Lightning component. It provides hooks into the rendering lifecycle of the component, enabling you to customize how the component is rendered, re-rendered, and un-rendered.

// ExampleComponentRenderer.js
({
    render: function (component, helper) {
        // Custom render logic
        var result = this.superRender();
        // Additional rendering logic
        return result;
    },
    rerender: function (component, helper) {
        // Custom rerender logic
        this.superRerender();
        // Additional rerendering logic
    },
    afterRender: function (component, helper) {
        this.superAfterRender();
        // Post-rendering logic
    },
    unrender: function (component, helper) {
        this.superUnrender();
        // Cleanup logic
    }
})

9. How to ensure FLS while working with Lightning Component?

Field-Level Security (FLS) is a critical aspect of Salesforce security, ensuring that users can only see or modify fields they are permitted to access. When working with Lightning Components, it’s essential to respect and enforce FLS to maintain data security. Here’s how you can ensure FLS while working with Lightning Components:

a. Use Apex to Check FLS

When you need to access field data in Lightning Components, use Apex controllers to enforce FLS. Apex provides methods to check whether the current user has read or edit access to specific fields.

Example:

Apex Controller (MyController.cls)

public with sharing class MyController {
    @AuraEnabled
    public static List<sObject> getRecords() {
        // Check if the user has read access to the fields
        if (Schema.sObjectType.Account.fields.Name.isAccessible() &&
            Schema.sObjectType.Account.fields.Industry.isAccessible()) {
            // Query only accessible fields
            return [SELECT Name, Industry FROM Account LIMIT 10];
        } else {
            // Handle the case where the user does not have access
            throw new AuthorizationException('You do not have access to the required fields.');
        }
    }

    @AuraEnabled
    public static void updateRecord(Id recordId, String newName) {
        // Check if the user has edit access to the fields
        if (Schema.sObjectType.Account.fields.Name.isUpdateable()) {
            Account acc = [SELECT Name FROM Account WHERE Id = :recordId LIMIT 1];
            acc.Name = newName;
            update acc;
        } else {
            // Handle the case where the user does not have access
            throw new AuthorizationException('You do not have permission to update the Name field.');
        }
    }
}

Lightning Component (MyComponent.cmp)

<aura:component controller="MyController">
    <aura:attribute name="records" type="Account[]"/>
    
    <lightning:button label="Load Records" onclick="{!c.loadRecords}" />
    <aura:iteration items="{!v.records}" var="record">
        <p>{!record.Name} - {!record.Industry}</p>
    </aura:iteration>
</aura:component>

Lightning Component Controller (MyComponentController.js)

({
    loadRecords : function(component, event, helper) {
        var action = component.get("c.getRecords");
        action.setCallback(this, function(response) {
            var state = response.getState();
            if (state === "SUCCESS") {
                component.set("v.records", response.getReturnValue());
            } else {
                console.error("Failed to load records: " + response.getError());
            }
        });
        $A.enqueueAction(action);
    }
})

b. Use Lightning Data Service (LDS)

Lightning Data Service (LDS) respects FLS and sharing rules automatically. When you use LDS, Salesforce ensures that the data returned to the Lightning Component respects the user’s FLS settings.

Example:

Lightning Component with LDS (MyLDSComponent.cmp)

<aura:component>
    <aura:attribute name="recordId" type="Id" />
    <force:recordData
        recordId="{!v.recordId}"
        targetFields="{!v.record}"
        layoutType="FULL"
        mode="VIEW" />
    
    <lightning:inputField fieldName="Name" />
    <lightning:inputField fieldName="Industry" />
</aura:component>

c. Use ui:outputText and force:recordData

Using ui:outputText for display and force:recordData to fetch records also ensures FLS is respected.

Example:

Lightning Component (MyForceComponent.cmp)

<aura:component>
    <aura:attribute name="recordId" type="Id" />
    <force:recordData
        recordId="{!v.recordId}"
        targetFields="{!v.record}"
        layoutType="FULL"
        mode="VIEW" />
    
    <ui:outputText value="{!v.record.Name}" />
    <ui:outputText value="{!v.record.Industry}" />
</aura:component>

10. Can we use fieldSet in the lightning component?

Yes, you can use field sets in Lightning components by retrieving the field set information through Apex and dynamically rendering the fields in the component. Here’s a brief outline:

Apex Controller: Retrieve field set fields.

public with sharing class FieldSetController {
    @AuraEnabled
    public static List<String> getFieldSetFields(String objectName, String fieldSetName) {
        Schema.FieldSet fieldSet = Schema.getGlobalDescribe().get(objectName).getDescribe().fieldSets.getMap().get(fieldSetName);
        List<String> fieldList = new List<String>();
        for (Schema.FieldSetMember f : fieldSet.getFields()) {
            fieldList.add(f.getFieldPath());
        }
        return fieldList;
    }
}

Lightning Component: Fetch and display the fields.

<aura:component controller="FieldSetController" implements="flexipage:availableForAllPageTypes" access="global">
    <aura:attribute name="objectName" type="String" />
    <aura:attribute name="fieldSetName" type="String" />
    <aura:attribute name="fields" type="List" />
    
    <aura:handler name="init" value="{!this}" action="{!c.doInit}" />
    
    <aura:iteration items="{!v.fields}" var="field">
        <lightning:inputField fieldName="{!field}" />
    </aura:iteration>
</aura:component>

Component Controller: Initialize and set fields.

({
    doInit: function(component, event, helper) {
        var action = component.get("c.getFieldSetFields");
        action.setParams({
            objectName: component.get("v.objectName"),
            fieldSetName: component.get("v.fieldSetName")
        });
        action.setCallback(this, function(response) {
            if (response.getState() === "SUCCESS") {
                component.set("v.fields", response.getReturnValue());
            }
        });
        $A.enqueueAction(action);
    }
})

11. How to navigate from one component to another component.

We can use force:navigateToComponent

OR we can use lightning:navigation

12. Can we use PageReference in Lightning Component?

Yes

13. How to call the Parent Component method from the child component without using events?

Yes. By using aura:action but the recommended way is to use Component Event

14. Can we use LWC inside Aura?

Yes. We can use

15. Can we use Aura Inside LWC?

No. We can only use LWC inside Aura but not vice versa

 16. Is Lightning an MVC framework?

No, it’s a component-based framework.

17. Which parts of Lightning Components are server-side and which are client-side?

Lightning Components use JavaScript on the client side and Apex on the server side.

18. Is there any limit on how many components to have in one Application?

No

19. Is Lightning Components replacing Visualforce? 

No

20. What is Aura? Why do we use the aura: namespace in the code?

Aura is a framework used by Salesforce to build dynamic, responsive web applications for mobile and desktop devices. It provides a robust component-based architecture that allows developers to create reusable components, making it easier to build and maintain large applications.

The aura: namespace is used in the code to reference built-in Aura components and features provided by the Aura framework. These components and features include fundamental building blocks such as aura:component, aura:attribute, aura:iteration, and event handling mechanisms like aura:handler. By using the aura: namespace, developers can leverage the predefined functionalities and structures that are integral to building and managing the behavior, data, and interaction of Lightning components within the Aura framework. This helps in maintaining consistency, reducing development time, and ensuring best practices are followed in building Salesforce Lightning applications.

21. What is the difference between Visualforce Components and Lightning Components ?

Visualforce Components are part of the traditional model used in Salesforce for creating UIs. They follow a page-centric model where the server generates the HTML and sends it to the client. Visualforce pages are tightly coupled with the Salesforce server and rely heavily on server-side processing. This model is suitable for simpler applications with less dynamic behavior.

Lightning Components, on the other hand, are part of the modern, client-centric framework known as the Lightning Component Framework (Aura framework). They follow a component-based architecture, where each component encapsulates its own HTML, CSS, and JavaScript. This enables more dynamic and interactive user interfaces that can run entirely on the client-side. Lightning Components support modular development, making it easier to build reusable components and maintain large-scale applications. They also provide better performance and responsiveness compared to Visualforce due to reduced server round-trips and more efficient client-side rendering.

22. Can we integrate Lightning components with another framework, such as Angular?

Yes. we can include the working 3rd party code inside a Visualforce Page, embed the Visualforce Page inside a Lightning Component. This Lightning Component can be used as any other Lightning Component in various environments.

23. What is use of @AuraEnabled annotation?

@AuraEnabled method is used to make any Apex Method for either Aura or LWC Component. @AuraEnabled Method must be static in nature.
Read more about @auraEnabled here.

24. What If I try to make any DML inside a method which is having @AuraEnabled(cacheable=true)?

If you try to make a DML inside the method then you will read only errors. cacheable=true makes the method read only.

25. How to Create a Component Dynamically?

Use $A.createComponent for creating the dynamic component see below code snippet.

​​<!--c:createComponent-->
<aura:component>
    <aura:handler name="init" value="{!this}" action="{!c.doInit}"/>

    <p>Dynamically created button</p>
    {!v.body}
</aura:component>
JS Code
/*createComponentController.js*/
({
    doInit : function(cmp) {
        $A.createComponent(
            "lightning:button",
            {
                "aura:id": "findableAuraId",
                "label": "Press Me",
                "onclick": cmp.getReference("c.handlePress")
            },
            function(newButton, status, errorMessage){
                //Add the new button to the body array
                if (status === "SUCCESS") {
                    var body = cmp.get("v.body");
                    body.push(newButton);
                    cmp.set("v.body", body);
                }
                else if (status === "INCOMPLETE") {
                    console.log("No response from server or client is offline.")
                    // Show offline error
                }
                else if (status === "ERROR") {
                    console.log("Error: " + errorMessage);
                    // Show error message
                }
            }
        );
    },

    handlePress : function(cmp) {
        // Find the button by the aura:id value
        console.log("button: " + cmp.find("findableAuraId"));
        console.log("button pressed");
    }
})

26. Can we navigate to one component from another component?

Yes. we can navigate for this we can use lightning:navigation. 

Below is the code for the same

({
   doInit : function(component, event, helper) {
 
   },
   navigate : function(component, event, helper) {
       var nagigateLightning = component.find('navigate');
       var pageReference = {
           type: 'standard__objectPage',
           attributes: {
               objectApiName: 'Account',
               actionName: 'list'
           },
           state: {
               filterName: 'MyAccounts'
           }
       };
       nagigateLightning.navigate(pageReference);
   }
})

27. Which Interface is used to make a component available inside Salesforce Digital Experience?

Ans: forceCommunity:availableForAllPageTypes

28. How can you ensure that a Lightning component respects Field-Level Security (FLS) when accessing and displaying data?

To ensure that a Lightning component respects Field-Level Security (FLS) when accessing and displaying data, you should use Apex controllers to handle data operations, as Apex provides methods to check FLS. In the Apex controller, use the Schema.sObjectType.<ObjectName>.fields.<FieldName>.isAccessible() method to check if the current user has read access to the fields and Schema.sObjectType.<ObjectName>.fields.<FieldName>.isUpdateable() to check for edit access. Additionally, using Lightning Data Service (LDS) is recommended as it respects FLS automatically, ensuring that only fields the user is permitted to see or edit are accessed. By performing these checks, you can enforce FLS in your Lightning components, maintaining data security and compliance with Salesforce’s security model.

Part – 2 | 50 LWC Lightning Web Component Interview Questions

Comments are closed.