LWC Enhancements for Developers | Winter'24 Edition

Lightning Web Components (LWC) is a powerful framework for building custom Salesforce applications. In the Winter '24 release, Salesforce is adding a number of new features to LWC, making it even more powerful and versatile.

There are plenty of new Lightning Web Components features to get excited about in the Winter ’24 release. Today I will share 5 essential features in Lightning Web Components that will ease our job as Salesforce developers.

Here are 5 new LWC features to get excited about:

1. New and Changed Directives for Lightning Web Components  - lwc:is

This new directive provides an imported constructor at runtime to the  <lwc:component> managed element enabling a component to instantiate another component dynamically.
Dynamic component creation can help you avoid loading large modules that you don’t need for all use cases. Also, you can create a component instance when the underlying component constructor isn’t known until run time. 


<template>
    <div class="container">
        <lwc:component lwc:is={componentConstructor}></lwc:component>
    </div>
</template>
<lwc:component> serves as a placeholder in the DOM that renders the specified dynamic component. You must use <lwc:component> with the lwc:is directive.

To use this feature, your organization must have Lightning Web Security enabled.

2. Create and Manage Toast Notifications - lightning/toast (Generally Available)

The LightningToast component displays a toast notification with an icon, label, message, and links. Use a toast to convey small pieces of information to the user, providing feedback and confirmation after the user takes an action. Toasts can disappear after a certain duration or until the user clicks the close button.

Customization

By default, the toast container shows a maximum of 3 toast notifications at the same time. Set the maxToasts attribute to change the maximum number of toasts shown at a time.
Toast components display at the top center of the container by default. The most recent toast displays at the top of the container, and the oldest toast notification displays at the bottom. Change the toasts' position in the container with the toastPosition attribute.

The container position is fixed to the viewport. Adjust the position of the container relative to its parent element with the containerPosition attribute. This attribute has two values :

  • fixed - positions the container relative to the initial containing block established by the viewport.

  • absolute - positions the container relative to a positioned parent element.
// c/myToastComponent.js
import { LightningElement } from 'lwc';
import ToastContainer from 'lightning/toastContainer';
import Toast from 'lightning/toast';
export default class MyToastComponent extends LightningElement {
    connectedCallback() {
        const toastContainer = ToastContainer.instance();
        toastContainer.maxToasts = 5;
        toastContainer.toastPosition = 'top-left';
    }
    Toast.show({
        label: 'This is a toast title with a {0} placeholder link that gets replaced
        by labelLinks ',
        labelLinks: [{
            'url': 'https://debugforce.blogspot.com/2023/08/5-must-try-new-features-in-salesforce.html',
            'label': 'Flow Enhancements in Winter '24'
        }],
        message: 'This message has a {0} placeholder link that gets replaced by from messageLinks ',
        messageLinks: [{
            url: 'https://debugforce.blogspot.com/',
            label: 'debug Force.com'
        }],
        mode: 'sticky'
        variant: 'info',
        onclose: () => {
            // Do something after the toast is closed
        }
    }, this);
}
}

The lightning/toastContainer module creates a container that handles and displays your page-level toast notifications. With lightning/toastContainer, you can:

  • Set the maximum number of toasts in the container using the maxToasts attribute.
  • Position the container using containerPosition.

3. Control Workspace Tabs and Subtabs - lightning/platformWorkspaceApi (Beta)

The lightning/platformWorkspaceApi module provides LWC Workspace API methods to control workspace tabs and subtabs in a Lightning console app.

We can use the LWC workspace API to manage workspace tabs and subtabs. Import the lightning/platformWorkspaceApi module to access the LWC Workspace API methods, wire adapters, and event-based APIs via Lightning Message Service.

NOTE Lightning Web Security must be enabled in the Salesforce org because Lightning Locker doesn’t support the LWC Workspace API.

All the methods in the lightning/platformWorkspaceApi module return a promise. Required method parameters are explicitly passed as individual arguments. Optional parameters are passed into an object as the last argument of the method.

These API methods for LWC are available for Lightning console apps.

  • closeTab()—Closes a workspace tab or subtab.
  • disableTabClose()—Prevents a workspace tab or subtab from closing.
  • focusTab()—Focuses a workspace tab or subtab.
  • getAllTabInfo()—Returns information about all open tabs.
  • getFocusedTabInfo()—Returns information about the focused workspace tab or subtab.
  • getTabInfo()—Returns information about the specified tab.
  • openSubtab()—Opens a subtab within a workspace tab. If the subtab is already open, the subtab is focused.
  • openTab()—Opens a new workspace tab. If the tab is already open, the tab is focused.
  • refreshTab()—Refreshes a workspace tab or a subtab specified by the tab ID.
  • setTabHighlighted()—Highlights the specified tab with a different background color and a badge. Tab highlights don’t
    persist after reloading a Lightning console app.
  • setTabIcon()—Sets the icon and alternative text of the specified tab.
  • setTabLabel()—Sets the label of the specified tab.
    These wire adapters are available for Lightning console apps.
  • EnclosingTabId()—Returns the ID of the enclosing tab.
  • IsConsoleNavigation()—Determines whether the app it’s used within uses console navigation.

Subscribe to these channels for the events that you want to listen for.

  • lightning__tabClosed—Indicates that a tab was closed.
  • lightning__tabCreated—Indicates that a tab was created successfully.
  • lightning__tabFocused—Indicates that a tab was focused.
  • lightning__tabRefreshed—Indicates that a tab was refreshed.
  • lightning__tabReplaced—Indicates that a tab was replaced successfully.
  • lightning__tabUpdated—Indicates that a tab was updated successfully.
4. Monitor Component Events - lightning/logger (Beta)

Add observability to your Lightning web components with the Custom Component Instrumentation API (beta). Now you can directly monitor and track events or interactions with custom Lightning web components in your org's Event Monitoring. Previously, Event Monitoring tools only tracked insights about your application as a whole, like records loaded and page performance. The Custom Component Instrumentation API is designed for Lightning web components and isn’t supported for Aura components.

Import log from the lightning/logger module in your component and log data messages to Event Monitoring. The log() function publishes data to a new EventLogFile event type called Lightning Logger Event that structures the event data for use in Event Monitoring.

<!-- monitorEventComponent.html -->
<template>
  <lightning-button label="Approve" 
                    onclick={handleClick}>
  </lightning-button>
</template>
// c/monitorEventComponent.jsimport { LightningElement } from 'lwc';
import { log } from 'lightning/logger';

export default class HelloWorld extends LightningElement {
  constructor() {
  super();
  }

  let msg = {
      type: "click",
      action: "Approve"
  }

  handleClick() {
    log(msg);
  }
}
5. Get the Latest LWC Features with Component-Level API Versioning

Add an API version on a custom component to inform the LWC framework to behave as it did for the Salesforce release corresponding to the API version for that component. Versioning your custom components allows us to ship new features, bug fixes, or performance improvements and to deprecate legacy features.

<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>58.0</apiVersion>
</LightningComponentBundle>
For example, setting the apiVersion key to 58.0 informs LWC that the custom component continues to behave as it did in Summer ’23.

NOTE: If you provide an apiVersion value that’s later than the available LWC API version, the latest-known version is used. For instance, if the latest LWC API versions are 58.0, 59.0, and 60.0, and you specify 61.0, then the framework uses 60.0. Similarly, if you specify a version earlier than 58.0, the framework uses 58.0.

I hope this article was helpful. And I would love to hear your feedback on the post.

Do you have any questions about the LWC enhancements in the Winter '24 release? Let me know in the comments below.

Reference:


Comments

Popular posts from this blog

Introducing Lightning Record Picker: A New Era of Record Selection

New Intelligence View for Leads and Contacts in Salesforce | Winter '24

Handling recursion in Apex Triggers