Skip to main content

Salesforce Lightning Web Components Overview

What are Lightning Web Components(LWC)?
Lightning web components are custom HTML elements built using HTML and modern JavaScript.

 Now you can build Lightning components using two programming models: Lightning Web Components, and the original model, Aura Components.

 Why we need to go for LWC?

1.It uses Core Web Components standards

2.Most of the code you write is standard JavaScript and HTML

3.Provides only what’s necessary to perform

4.It is built on code that runs natively in browsers

5.It is lightweight and delivers exceptional performance

 Where can we implement LWC Components?

Salesforce Developer Console won’t support LWC components. We need to install Visual Studio Code(VS Code) Editor to implement the LWC Components.

LWC Component Bundle Structure:
LWC Majorly contains 3 files
HTML
JavaScript
Meta XML


Naming Convention/Rules for Components Bundles

1.Component name Must begin with a lowercase letter

2.Name must contain only alphanumeric or underscore characters

3.Can’t contain a hyphen (dash)

4.Must be unique in the namespace (No other Aura or LWC can have this name)

5.Can’t include whitespace

6.Can’t end with an underscore

7.Can’t contain two consecutive underscores

8.Folder and files names must have same “prefix name”


What are the Decorators available in LWC?

We have 3 Decorators in Lightning Web Components. Variables declared with below decorators in LWC components.

1) @api
2) @track
3) @wire

@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.
 
ex: @api itemName = 'New Item';


@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. 
ex: @track firstName = '';

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

@wire(getRecord, { recordId: '$recordId', fields: FIELDS })

  contact;


No Expressions in the HTML

 There is no expression available in the LWC HTML markup as it used to be for Lightning Components. E.g., the code below does not work in LWC:

 {!expression} // not supported in LWC

 Instead you will need to bind a property in the HTML to properties in the JS class. Example below:

{greeting} 

 

Using Apex Controllers

The Apex controllers follow the same syntax as they used to for enabling server side communication with Lightning Components. The Apex controllers still use @AuraEnabled annotation to integrate with LWC, the change however is more on the syntax on JS side of the LWC. More can be found on the documentation.

 

Events in Lightning Web Components

Lightning web components do not have Lightning Component equivalent of component or application events. The events in LWC are dispatched using standard DOM events.

 Standard DOM events are used to communicate up in the component hierarchy (similar to component events in LC)

To communicate between components not in the hierarchy, publish-subscribe event model is utilized.

 

Interoperability between Lightning Web Components and Lightning Components

 Aura and LWC can be able to communicate using Public API’s and Events.

LWC can be embedded inside Aura Components, but Aura Components cannot be embedded inside LWC.

 Syntax Differences:












Sample component:
To display the Full Name in upper case letters based on the two input parameters First Name and Last Name.

HTML File(hello.html)
<template>
    <lightning-card title="HelloExpressions" icon-name="custom:custom14">
        <div class="slds-m-around_medium">
            <lightning-input
                name="firstName"
                label="First Name"
                onchange={handleChange}
            ></lightning-input>
            <lightning-input
                name="lastName"
                label="Last Name"
                onchange={handleChange}
            ></lightning-input>
            <p class="slds-m-top_medium">
                Uppercased Full Name: {uppercasedFullName}
            </p>
        </div>
    </lightning-card>
</template>


JavaScript File(hello.js)
import { LightningElement } from 'lwc';


export default class HelloExpressions extends LightningElement {
    firstName = '';
    lastName = '';


    handleChange(event) {
        const field = event.target.name;
        if (field === 'firstName') {
            this.firstName = event.target.value;
        } else if (field === 'lastName') {
            this.lastName = event.target.value;
        }
    }


    get uppercasedFullName() {
        return `${this.firstName} ${this.lastName}`.trim().toUpperCase();
    }
}



JS-Meta.XML(hello.js-meta.xml)
xml version="1.0" encoding="UTF-8" ?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>48.0</apiVersion>
    <isExposed>true</isExposed>
    <targets>
        <target>lightning__AppPage</target>
        <target>lightning__RecordPage</target>
        <target>lightning__HomePage</target>
    </targets>
</LightningComponentBundle>


Sample Output:

Comments

Popular posts from this blog

Get started with Simple Lightning Web Component(Bike Card)

Lightning web component HTML files all include the template tag. The template tag contains the HTML that defines the structure of your component. Let’s look at the HTML for a simplified version of the component. Paste the following into app.html (replacing any existing HTML in the file). bikeCard.html < template > < div id = "waiting" if : false = { ready } > Loading.. </ div > < div id = "dispaly" if : true = { ready } > < div > Name: {name} </ div > < div > Description: {description} </ div > < div > Category: {category} </ div > < div > Material: {material} </ div > < div > Price: {price} </ div > < div >< img src = { pictureURL } /></ div > </ div > </ template > The identifiers in the curly braces {} are bound to the fields of the same name in the corresponding JavaScript class. Here’s a JavaScript file to s...

Disable Document Download in Salesforce

Disable downloads for certain users based on the name of the file uploaded to Salesforce. We can use the following example code inside of a Apex class. This code essentially prevents files whose file name starts off with Kaipu- from being downloaded by anyone whose user role’s developer name is not Kaipu_Sales. Modify this code to suit your own purpose. Based on Role: public class ContentDownloadHandlerFactoryImpl implements Sfc.ContentDownloadHandlerFactory {    public Sfc.ContentDownloadHandler getContentDownloadHandler(List<ID> ids, Sfc.ContentDownloadContext context) {      // See if the user has the Kaipu Sales role (based on developer name field).      Boolean isSecretUser = [        SELECT Id        FROM UserRole        WHERE ID = :UserInfo.getUserRoleId()          AND DeveloperName = ' Kaip...

Commonly asked Lightning Developer Interview Questions & Answers

1. Where can we use Lightning Components? We can use Lightning Components in the following places: Drag-and-drop Components in the Lightning App Builder and Community Builder. Add Lightning Components to Lightning Pages. Add Lightning Components to Lightning Experience Record Pages. Launch a Lightning Component as a Quick Action Override Standard Actions with Lightning Components Create Stand-Alone Apps 2. How do you build Lightning Components? We can build Lightning Components using two programming models: the Lightning Web Components model, and the original Aura Components model. 3. How can you create Lightning Record Pages in Salesforce, and what are the different types? We can make use of Lightning App Builder for creating Lightning Record Pages, to create the following three types of pages: App Page Home Page Record Page 4. What options are there for Lightning Record Page assignment? “Lightning Pages” can be assigned at three different levels: The org default App default – this ov...