Component Composition in LWC

Component Composition in LWC

On November 8, 2022, Posted by , In LWC Tutorial, With Comments Off on Component Composition in LWC
Component Composition in lwc

Component composition in Lightning Web Components (LWC) refers to the practice of building complex user interfaces by combining multiple smaller components into a larger, more complex component. This approach leverages the encapsulation and reusability features of LWC to create modular, maintainable, and scalable applications.

An event is a signal that some action has taken place. There are many types of events like keyboard events, mouse events, etc.

For sake of understanding, we are dividing events into two broad types.

Browser Events:

Browser events in Lightning Web Components (LWC) are fundamental interactions captured from the user’s environment, such as clicks, key presses, mouse movements, and more. These events help LWC components respond to user actions in a dynamic and interactive way. Developers can listen for these native events directly within their components using standard HTML event handlers like onclick , onchange , or more specialized ones like onmouseenter .

LWC also supports the use of event handlers in the JavaScript class, where developers can attach listeners to elements in the template during the component’s lifecycle. This method of capturing and handling browser events makes LWC highly responsive and interactive, facilitating a seamless user experience.

Custom Events in LWC

Custom events in LWC allow developers to create their own specific events that are not part of the standard browser event system. These are particularly useful for communicating specific state changes or actions from child components to parent components, enabling a clear and controlled component interaction model.

To define a custom event in LWC, a developer can use the CustomEvent interface, specifying an event name and an optional configuration object which can include data to be passed to the event handler. The event is then dispatched from the child component using the dispatchEvent method. Parents listening for this event can react accordingly, managing application flow and ensuring components can operate independently yet cohesively within larger applications. This architecture supports the encapsulation and modularity of components, key principles of the LWC framework.

Event Handlers:

Event handlers in Lightning Web Components (LWC) play a critical role in making components interactive and responsive to user actions. They are JavaScript functions defined within the component’s class that handle the events triggered by various user interactions, such as clicking a button, entering data into a form, or hovering over an element. These handlers are attached directly to elements in the component’s HTML template using the on[eventname] syntax, such as onclick , onchange , and onmouseover .

In LWC, event handlers can also handle custom events emitted by child components, which allows for complex, component-based event handling structures. The framework’s reactivity system ensures that any data changes affecting the DOM in response to events are efficiently processed and updated, maintaining high performance even in dynamic and data-heavy applications.

Event handlers can be further optimized in LWC by using event modifiers, which are special directives that alter how events are handled. For instance, modifiers can specify event handling at the capture phase instead of the bubbling phase, prevent default actions, or stop the propagation of events up the DOM tree. This fine-grained control over event handling allows developers to create highly customized user experiences and interactions within their applications.

By leveraging both native browser events and custom events, along with sophisticated event handling strategies, developers can effectively manage user interactions, data flow, and component lifecycle events within their LWC applications.

To bind event handler ( javascript function) on a template we use event name with “on”  keyword as a prefix for example for click event we will write as     

“ onclick={eventHandlerName}”

Let’s take a look at examples now : 

Example 1: 

We are simply taking input from the user then on the “change” event we are sending value to the javascript event handler (function ie handleChange)

We have used if:true and If:false directive to render the div portion depending on whether the value of {even} evaluates to true or false.

Note: Content is removed from DOM not just hidden on UI ie you can’t find the element even in the browser console.

  • In the Javascript file, we have created a getter by the name “even” which computes the mod of the number and returns true if the number is even.
  • handleChange” is an event handler where we have passed the event object.
  • Event objects are standard javascript object which contains all the information about an event that has occurred for instance in our case we used an event object to get the value that the user entered in the text field.


----- JS -------import { LightningElement } from "lwc";export default class Basic1 extends LightningElement {  number = 0; get even(){    return this.number % 2 === 0 ? true  : false ; } handleChange(event){     this.number =; }}----END -------------HTML ------<template>     <lightning-card variant="Narrow" title="Basic 2" icon-name="standard:account">         <lightning-input class = "slds-var-m-around_medium" type="number" variant="standard" name="Number" label="Number" placeholder="Enter the number" onchange={handleChange}></lightning-input>                <!-- Notice how we used directives to add or remove div element from DOM depending on what is returned by {even} -->        <div class= "slds-var-m-around_medium" if:true ={even}>            Number you have entered is even number        </div>        <div class="slds-var-m-around_medium" if:false ={even}>            Number you have entered is odd number        </div>    </lightning-card></template>


Example 2 : 

In the below HTML file, we have added two lightning cards one for each type of directive (for:each and iterator:iteratorName)

When using for:each directive we pass the whole list in for:each ={listofItems} and for:item=”item” represents current item in the iteration.

As you will notice we have also a “key” attribute to the “li” element as without a key attribute we cant use either of the aforementioned directives.

We are simply displaying name property from contact object by accessing current item ie “con” and using “.” notation to access object property as “” and as we read earlier we use braces to bind the properties and hence {}

In Iterator directive we pass array as iterator:it={listName}. In iterator we cant access the property of the current item directly like we did in for:each rather we have to use the “value” keyword for example “ it.value.Id” or “it.value.Name” 

As we discussed earlier iterator has two special properties to identify the first and the last item which we can use to add any special effect. We can access first and last element by using {it.first} or {it.last}.

Both the {it.first} and {it.last} return the boolean value ie true or false and hence are  are used with if:true directive to manipulate the content

Note: “it” is the iterator name you can choose any name for your iterator.

JS : 

JS here only holds a simple object with predefined values in it.


-----JS-----import { LightningElement } from "lwc";export default class Basic1 extends LightningElement {  primitiveData;  contacts = [    {        Id: 1,        Name: 'Amy Taylor',        Title: 'VP of Engineering',    },    {        Id: 2,        Name: 'Michael Jones',        Title: 'VP of Sales',    },    {        Id: 3,        Name: 'Jennifer Wu',        Title: 'CEO',    },];}-----END -----------HTML----<template>     <lightning-card variant="Narrow" title="For Each Loop" icon-name="standard:account">         <div class="slds-var-m-around_medium">            <template for:each={contacts} for:item="con">                <li key={con.Id}>                    {con.Name}                </li>            </template>        </div>    </lightning-card>    <lightning-card variant="Narrow" title="Iterator Loop" icon-name="standard:account">        <div class="slds-var-m-around_medium">            <template iterator:it={contacts}>                <ul key={it.value.Id}>                    <div if:true={it.first} class="list-first">                    </div>                    <li>{it.value.Name}</li>                    <div if:true={it.last} class="list-last">                    </div>                </ul>            </template>        </div>    </lightning-card></template>

Output :

For those looking for Salesforce learning, CRS Info Solutions provides an extensive Salesforce training program designed to enhance your skills and career opportunities. Explore our Salesforce training in Bangalore to gain practical, hands-on experience, real-time projects included. Our training covers all essential aspects of Salesforce, ensuring comprehensive learning, providing daily notes, interview questions, certification preparation and job prep guidance. Enroll for Free demo tod

Comments are closed.