Showing posts with label LWC Interview Questions. Show all posts
Showing posts with label LWC Interview Questions. Show all posts

Saturday, August 1, 2026

Lightning Web Components Interview Questions- Part 5


36. What is the lightning/graphql module, and how is it different from the older lightning/uiGraphQLApi?

lightning/graphql is a newer LWC module for working with Salesforce’s GraphQL API, and it supersedes lightning/uiGraphQLApi. Its most notable addition is support for dynamic queries — instead of a fully static query string, you can build part of the query at runtime using JavaScript string interpolation (${variableName}) inside the gql tagged template literal, and the variable’s value is resolved and inserted into the query when it runs. This makes a single component’s query genuinely reusable across different objects or filter conditions, rather than needing a hardcoded query per use case.

import { gql } from 'lightning/graphql';

const query = gql`
  query getRecords {
    uiapi {
      query {
        ${this.objectName} {
          edges {
            node {
              Id
              Name { value }
            }
          }
        }
      }
    }
  }
`;

37. How do GraphQL mutations work in LWC as of Spring ’26?

Before Spring ’26, the GraphQL wire adapter in LWC was read-only — you could query data, but any create, update, or delete still had to go through Apex or lightning/uiRecordApi. Spring ’26 added an executeMutation function, imported from lightning/graphql, which lets you perform create/update/delete operations imperatively, directly from your JavaScript, using the same gql template literal syntax as queries.

import { executeMutation, gql } from 'lightning/graphql';

const UPDATE_ACCOUNT = gql`
  mutation UpdateAccount($input: AccountUpdateInput!) {
    uiapi {
      AccountUpdate(input: $input) {
        Record {
          Id
          Name { value }
        }
      }
    }
  }
`;

async function updateAccount(accountId, newName) {
    await executeMutation({
        query: UPDATE_ACCOUNT,
        variables: { input: { Id: accountId, Name: newName } }
    });
}

This matters practically because it cuts out an entire layer of Apex for straightforward CRUD operations — fewer controller classes, fewer test classes, and a component that can own its full data lifecycle (read and write) through one GraphQL surface instead of mixing GraphQL reads with Apex writes.

38. What is TypeScript support in LWC, and is it production-ready?

As of Spring ’26, TypeScript support for LWC is still in developer preview — not generally available. That’s an important nuance for an interview: candidates should know it exists, but also know not to overstate its maturity.

The most concrete addition is the @salesforce/lightning-types npm package, which provides official TypeScript type definitions for base components (like lightning-input or lightning-button). This replaces the custom type-definition files many teams previously wrote by hand. Salesforce DX’s MCP server also includes a tool that helps convert existing JavaScript-based LWC to TypeScript, which is meant to accelerate migration for larger codebases rather than requiring a full manual rewrite.

import type { LightningInput } from '@salesforce/lightning-types';

handleChange(event: CustomEvent) {
    const input = event.target as LightningInput;
    console.log(input.value, input.validity.valid);
}

39. What is Local Dev (Beta), and how does it change the LWC development workflow?

Local Dev is a local, single-component preview environment. As of Winter ’26, it supports access to platform modules directly during local preview — including Lightning Data Service wire adapters, @salesforce scoped modules, and Apex controllers. Previously, a lot of local component preview tooling couldn’t reach these platform-connected pieces, which meant developers had to deploy to a sandbox just to see how a component behaved against real data or Apex logic. Local Dev closes that gap, at least for single-component iteration.

40. What are complex template expressions in LWC, and what do they unlock?

Historically, LWC templates only allowed simple property references or getters — no inline logic beyond that. A beta feature expands what a template expression can contain, allowing more complex JavaScript expressions directly in the template rather than requiring every computed value to be pushed into a getter in the JavaScript class. This is a quality-of-life change more than an architectural one, but it reduces boilerplate for components with a lot of small derived display values.

41. Can Lightning Web Components be used as local actions in screen flows now?

Yes — as of Winter ’26, LWC can be used for local actions in screen flows. Local actions run entirely client-side (in the browser), which means they can access browser-native functionality using JavaScript without a server round-trip. Because a local action doesn’t need to render a visible UI element in the flow itself, components built for this purpose should use a blank HTML template — the component does its work invisibly as part of the flow’s execution.

42. What is SLDS 2.0, and does it break existing LWC styling?

SLDS 2.0 became generally available as of Winter ’26. It introduces updated component designs, styling hooks, and utilities, along with a beta dark mode option for custom themes (currently limited to the Starter edition). For LWC specifically, the practical concern is the design token variable syntax: the older --lwc- camelCase prefix syntax used in SLDS 1 doesn’t carry over the same way in SLDS 2, so components relying on that older syntax should migrate to the equivalent global styling hook rather than assuming it will keep working unchanged. Salesforce also improved the SLDS linter with additional validation rules and quick fixes specifically to help with this transition.

43. How does Lightning Out 2.0’s authentication model compare to the original Lightning Out (Beta)?

This is covered in depth in Part 3 of this series, but as a quick recap for anyone reading this part standalone: the original Lightning Out (Beta) used session-ID-based authentication passed to the external host page, which was fragile and offered weaker isolation. Lightning Out 2.0, generally available since Winter ’26, instead uses OAuth 2.0 combined with the UI Bridge API — the external app requests authorization, receives a token, and exchanges it for a short-lived, purpose-specific Frontdoor URL used to render the embedded component inside an isolated iframe with its own shadow DOM.

44. What is Lightning Web Security, and why does it matter for a 2026 interview specifically?

Also covered in depth in Part 2, but worth restating here because it’s one of the two most authentication/security-relevant topics on this list: Lightning Web Security (LWS) replaced Lightning Locker as Salesforce’s client-side security architecture, became the default for new orgs in Winter ’23, and reached full general availability for both LWC and Aura components in Summer ’23. It uses a JavaScript sandbox with runtime “distortions” instead of Locker’s secure wrapper objects, which allows custom elements and third-party web components that Locker used to block, while still preventing unsafe cross-namespace access.

45. If an interview focuses heavily on security and authentication, what should a candidate prioritize from this list?

Out of everything covered in this part, two topics carry the most weight for a security- or architecture-focused round: Lightning Web Security (client-side sandboxing and its replacement of Locker) and Lightning Out 2.0’s OAuth-based authentication model (replacing the old session-ID approach for embedding components externally). Being able to explain not just what changed, but why the new approach is more secure — shorter-lived, more narrowly scoped credentials, and stronger isolation boundaries — tends to distinguish a candidate who has actually kept up with the platform from one reciting older material.

Sunday, September 26, 2021

Lightning Web Components Interview Questions- Part 4

33. How can we get the 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';

Supported properties include:

  • Id — the ID of the current site.
  • basePath — the section of the site’s URL that comes after the domain. For example, if your site domain 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.
// demoSite.js
import { LightningElement } from 'lwc';
import Id from '@salesforce/community/Id';

export default class CommunityPage extends LightningElement {
    // component logic here
}

34. How do we access LWC in Lightning App Builder?

We need to use targets to define where we want to use the LWC component. The example below supports the Record Page, Home Page, and App Page. We also need to set isExposed to true, and we can provide different properties on different screens using targetConfigs.

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

35. What are all the supported targets for LWC?

Experience Builder:

To make your component usable in Experience Builder, set isExposed to true. Then, in targets, add one of these values:

  • lightningCommunity__Page — create a drag-and-drop component that appears in the Components panel
  • lightningCommunity__Page_Layout — create a page layout component for LWR sites that appears in the Content Layout window
  • lightningCommunity__Theme_Layout — 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>

Flow (screen actions and, as of Winter ’26, local actions):

<target>lightning__FlowScreen</target>

Outside Salesforce entirely: as of Winter ’26, custom LWC can also be embedded in external, non-Salesforce apps using Lightning Out 2.0 (see Part 3, Question 22) — this doesn’t use the targets configuration above, but is configured separately as a Lightning Out 2.0 app in Setup.

For further reading, see the official Lightning Web Components documentation.


This concludes the 4-part Lightning Web Components Interview Questions series — 35 questions from beginner through 2026-current, interview-ready material.

Lightning Web Components Interview Questions-Part 3

22. How can we use Lightning Web Components outside Salesforce, and how does authentication work?

Since Winter ’26, the recommended way to do this is Lightning Out 2.0, which replaced the original Lightning Out (Beta) entirely. Key points that matter for an interview:

  • Lightning Out 2.0 is built on Lightning Web Runtime (LWR) and only supports embedding custom LWC (not Aura components, and not standard base components directly — those need to be wrapped in a custom LWC first).
  • Authentication is the biggest change. The original Lightning Out (Beta) relied on fragile session-ID-based authentication passed to the host page. Lightning Out 2.0 instead uses OAuth 2.0 together with the UI Bridge API: the external app requests authorization from Salesforce, receives a token, and exchanges it for a temporary secure Frontdoor URL used to render the embedded component.
  • Embedded components render inside iframes with a shadow DOM for stronger isolation than the original beta offered, which ran components directly on the host page without that separation.
  • You can override styles and properties of the embedded component and communicate between the component and the external app using app events.
  • Known limitations (as of GA): only custom LWC is supported (no Aura, no direct standard/base components), authenticated access is required (no public/anonymous embedding yet), and the external app’s browser must allow third-party/cross-origin cookies for the Salesforce session.

For validation-style interview questions on this topic, the key thing candidates should articulate is why the OAuth-based model is more secure than the old session-based one — it avoids exposing long-lived session identifiers to the host page and scopes access through short-lived, purpose-specific tokens instead.

23. Is it possible to iterate a Map in Lightning Web Components?

There’s no native out-of-the-box support for iterating a Map directly in an LWC template. The common workaround is converting the Map’s entries into an array of key-value pair objects in your JavaScript controller (for example, using Array.from(myMap) or a custom transformation), and then iterating that array with for:each in the template.

24. How do we iterate an sObject list in Lightning Web Components?

There’s no native out-of-the-box support for rendering a generic sObject’s fields dynamically. The typical approach is to query the object’s describe information (via getObjectInfo / getPicklistValues wire adapters or an Apex helper) to get field metadata, then dynamically build a list of field-value pairs in JavaScript that the template can iterate with for:each.

25. How do we access labels in Lightning Web Components?

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

Custom labels imported this way are automatically available for use in your JavaScript controller and can be exposed to the template through a getter.

26. What is the Lightning Message Service?

Lightning Message Service (LMS) is a publish-subscribe messaging system that enables communication across the DOM between components that aren’t in a direct parent-child relationship — including Visualforce pages, Aura components, and Lightning Web Components. Components publish messages to a shared message channel, and any component subscribed to that channel receives the message, regardless of where it sits in the page hierarchy.

27. How do we access events in Lightning Web Components?

Components communicate up the hierarchy (child to parent) by dispatching a CustomEvent. The parent listens for that event using the standard on + event name syntax in its template.

// child.js
this.dispatchEvent(new CustomEvent('itemselected', { detail: this.itemId }));
<!-- parent.html -->
<c-child onitemselected={handleItemSelected}></c-child>

28. Where can you use/access Lightning Web Components in Salesforce?

We can use LWC in Flow, Lightning App Builder (Record, App, and Home pages), Lightning Communities (Experience Cloud), the Utility Bar, a standalone Aura app, Custom Tabs, Visualforce, and — as of Winter ’26 — as local actions in screen flows, and outside Salesforce entirely via Lightning Out 2.0.

29. Explain styling hooks for Lightning Web Components, and how they relate to design tokens.

Styling hooks are now Salesforce’s primary recommended approach for customizing the default appearance of LWC-based Base Components (like lightning-button or lightning-card), rather than custom Aura design tokens. Styling hooks are CSS custom properties exposed specifically for supported customization, so your overrides won’t silently break when Salesforce updates a base component’s internal markup — unlike unsupported selector overrides.

Since Winter ’24, Salesforce specifically recommends global color styling hooks over custom Aura tokens for new development, largely to align with WCAG 2.1 color contrast standards. With SLDS 2.0 (generally available as of Winter ’26), styling hooks are also the approach that stays compatible going forward, since some older token variable syntax doesn’t carry over cleanly to SLDS 2.

30. What are Aura Tokens, and are they still relevant in 2026?

Design Tokens are named entities that store visual design attributes, used in place of hard-coded values (like hex colors or pixel spacing) to keep a design system scalable and consistent.

They still work and are still supported, but as of 2026 they’re considered the legacy approach — Salesforce recommends styling hooks (Question 29) for new components. Aura tokens remain relevant mainly for maintaining older components or for the small set of use cases styling hooks don’t yet cover.

To create a tokens bundle: in the Developer Console, select File → New → Lightning Tokens. The first tokens bundle should be named defaultTokens; tokens defined within it are automatically accessible in your Lightning components, while tokens in any other bundle require importing into defaultTokens to be accessible.

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

31. How can you use Aura Tokens and SLDS Design Tokens in LWC?

To use a custom Aura Token in LWC, reference it as a CSS custom property in your stylesheet:

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

LWC can also use any Lightning Design System design token marked with Global Access:

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

Note: this --lwc- camelCase syntax works in SLDS 1 but doesn’t carry over the same way in SLDS 2 (GA Winter ’26) — if you’re building or migrating components on SLDS 2, use the equivalent global styling hook instead of the older token variable syntax.

32. What are the notable LWC platform updates from 2025–2026 that a developer should know about?

A few recent changes are increasingly likely to come up in interviews, since they’ve shipped across Winter ’26 and Spring ’26:

  • Lightning Out 2.0 (see Question 22) — the new OAuth-based way to embed LWC in external apps, GA as of Winter ’26.
  • lightning/graphql module — a new GraphQL wire adapter module that supersedes the older lightning/uiGraphQLApi, adding support for dynamic queries built with JavaScript string interpolation inside the gql tagged template literal.
  • GraphQL mutations — Spring ’26 added an executeMutation function to lightning/graphql, allowing imperative create/update/delete operations directly through GraphQL instead of routing every write through Apex or lightning/uiRecordApi.
  • TypeScript support — still in developer preview, not GA, as of Spring ’26. The @salesforce/lightning-types npm package now provides official type definitions for base components (replacing custom type-definition files developers previously wrote themselves), and Salesforce DX’s MCP server includes a tool to help convert existing JS-based LWC to TypeScript.
  • Local Dev (Beta) — a local component preview that, as of Winter ’26, supports platform modules like Lightning Data Service wire adapters, @salesforce scoped modules, and Apex controllers, making local iteration faster without a full deploy cycle.

A well-prepared 2026 candidate should be able to name at least Lightning Out 2.0 and Lightning Web Security, since both directly touch security and authentication — the areas most likely to come up in a technical or architecture-focused interview round.

Lightning Web Components Interview Questions- Part 2

11. How can we access elements in the controller?

We have two methods available: this.template.querySelector() and this.template.querySelectorAll().

<!-- 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 a Boolean property?

False. We should give a default value if we want to update the value later.

13. How can we load a third-party JavaScript (JS) library in Lightning Web Components (LWC)?

We have a few ways to load a 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
    }
}

A couple more methods are available here — load a single script without CSS:

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

Load multiple files:

Promise.all([
    loadScript(this, resourceName + '/lib1.js'),
    loadScript(this, resourceName + '/lib2.js'),
    loadScript(this, resourceName + '/lib3.js')
]).then(() => { /* callback */ });

Note: whether a given third-party library works smoothly depends on your org’s client-side security architecture — see Question 21 below on Lightning Web Security, since it handles global objects and sandboxing differently than the older Lightning Locker.

14. Is it possible to call a third-party API from LWC JS, and what controls that access?

By default, browser-side JavaScript in LWC can’t make WebSocket connections or calls to third-party APIs. To allow it, the target domain must be added as a CSP Trusted Site in Setup — this is separate from Apex’s Remote Site Settings, which govern server-side callouts instead.

This is enforced by Salesforce’s client-side security architecture. Since Winter ’23, new orgs default to Lightning Web Security (LWS), which replaced the older Lightning Locker; LWS has been generally available for all orgs (LWC and Aura) since Summer ’23. LWS uses a JavaScript sandbox with “distortions” (rewriting risky APIs at runtime) instead of Locker’s secure wrapper objects, which makes it both more standards-compliant and generally faster, and it supports custom elements and third-party web components that Locker used to block outright. Whether a specific third-party library will “just work” in your component often depends on which of the two architectures your org is running.

15. How do you access a static resource?

Import it the same way as any static resource:

import resourceName from '@salesforce/resourceUrl/resourceName';

Then reference it in your component to load images, styles, or other static assets bundled in the resource.

16. How do you get the current User ID?

Import the Id property from the @salesforce/user scoped module:

import USER_ID from '@salesforce/user/Id';

This gives you the current running user’s Id directly, without needing an Apex callout.

17. How can we make changes to a component’s body after it’s 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 for a one-time operation, use a boolean field like hasRendered to track whether renderedCallback() has already executed — the first time it runs, perform the one-time operation and set hasRendered = true; if hasRendered is already true, don’t perform the operation again.

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 as well — public methods are part of a component’s API, and owner/parent components can call JavaScript methods on child components to communicate down the containment hierarchy.

@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 used in a template), the component rerenders and displays the new value. There’s one specific 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 automatically, so decorate the field with @track to tell the framework to observe changes to the properties of an object or the elements of an array.

@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 do you call Apex from Lightning Web Components?

Import the Apex method using its fully qualified reference, then either wire it reactively or call it imperatively:

import getContactList from '@salesforce/apex/ContactController.getContactList';

Using @wire, the method is called automatically and the component rerenders when the data changes. Calling it imperatively (as a plain function returning a Promise) gives you more control over exactly when the call happens, such as inside a button click handler.

20. How can we use Lightning Web Components in Visualforce?

LWC can be embedded in a Visualforce page by wrapping it in an Aura component first (since Visualforce can only host Aura components directly), then embedding that Aura wrapper on the Visualforce page using the <apex:includeLightning /> tag and the $Lightning.use() / $Lightning.createComponent() JavaScript APIs.

21. What is Lightning Web Security (LWS), and how is it different from Lightning Locker?

Lightning Web Security is Salesforce’s current client-side security architecture for Lightning components, and it replaced the older Lightning Locker. Key differences relevant in an interview:

  • Locker isolated components using secure wrapper objects around window, document, and other globals, plus proxy objects — this blocked custom elements and most third-party web components outright, and could add runtime overhead.
  • LWS instead runs each namespace in its own JavaScript sandbox and uses “distortions” — rewriting how risky APIs behave at runtime — to prevent unsafe actions while allowing custom elements, third-party web components, and libraries that manipulate global objects, since those changes don’t leak across namespace sandboxes.
  • Adoption timeline: LWS became generally available in Spring ’22, is the default security architecture for all orgs created since Winter ’23, and became fully generally available for both LWC and Aura components across all orgs in Summer ’23.
  • Practical impact: LWS generally requires no code changes for well-behaved LWC, since existing components already follow secure coding conventions — but orgs with legacy Aura components or managed packages that rely on Locker’s specific wrapper behavior should test in a sandbox before enabling it, since Locker-era workarounds can behave differently once distortions apply instead.

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.

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?

A component bundle contains:

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 component HTML conditionally?

To render HTML conditionally, add the if:true|false directive to a nested <template> tag that encloses the conditional content.

4. How do we 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 do we pass data from HTML to the 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 the same event handler 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>
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 do we iterate a list in Lightning Web Components (LWC)?

We have two options available here:

for:each — use for:item="currentItem" to access the current item. 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">
    <li key={contact.Id}>
        {contact.Name}, {contact.Title}
    </li>
</template>

Iterator — to apply special behavior to the first or last item in a list, use the iterator directive, iterator:iteratorName={array}, on a template tag. Use iteratorName to access these properties: value (the item’s value), index, first (boolean), and last (boolean).

<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 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 render() must be a template reference — 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 public properties in a 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 do you set a property from a parent component to a 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 do we pass data from a parent component to a child component?

LWC supports 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 — if the component tries to change the content, we get errors in the console.

We can pass primitive data types as most components support this without restriction.