Download as pdf or txt
Download as pdf or txt
You are on page 1of 99

Lightning Web Component

Develop more secure, fast and lightweight Component


Author: Debasis Jena
PAGE 1
What is Lightning web component ?

 new programming model for building Lightning components


 are custom HTML elements built using HTML and modern JavaScript
Framework
 is a stack of modern lightweight frameworks built on the latest web standards
 Lightning Web Components is lightweight and delivers exceptional
performance

PAGE 2
Visualforce VS Aura

VisualForce Aura Component


Server-Side: Client side:
- User requests a page . - The user requests an application or a
- The server executes the page’s underlying component .
code and sends the resulting HTML to the - The application or component bundle is
browser . returned to the client
- The browser displays the HTML - The browser loads the bundle
- The JavaScript application generates the UI
when the user interacts with the page, the
JavaScript application modifies the user
interface as needed

PAGE 3
Aura VS LWC

Aura Component LWC


utilize Aura framework for development and utilize browser provided features for general
execution of Lightning components component scaffolding along with Salesforce
Lightning web components framework

PAGE 4
Web Components
- a new browser feature that provides a standard component model for the Web
❖ Custom Elements: The HTML elements with custom templates, tag names like and behaviours are made
with a set of JavaScript APIs.
❖ Shadow DOM : is a standard that encapsulates the internal document object model (DOM) structure of a
web component.
❖ HTML templates: User-defined templates in HTML are rendered only when called upon
❖ ES Modules: ES Modules specification defines the inclusion and reuse of JS documents in a standard
based, modular, performant way

PAGE 5
The 2014 Webstack

-a rendering engine, standard elements,


events, and a core language (ECMAScript
5)
- Rendering wasn’t optimized for
continuous UI transformation
- Standard UI elements were complex
and did not support custom elements

To fulfil the gap:


-different scripting library being used
like CommonJs, React
-different framework with different
component model
- Optimize rendering with other
framework too

PAGE 6
The 2019 Webstack

-Common component model


- Common programming model
- Interoperable components
- Better performance because core
features are implemented natively in
web engines

PAGE 7
The 2019 Webstack - Lightning Web Components

LWC Provides a layer of specialized salesforce


service on top of Webstack
- Base Lightning Components
- Lightning Data Service
- User Interface API

PAGE 8
The Webstack transformation

PAGE 9
Coexistence and interoperability of AURA and LWC

PAGE 10
Why do you go for LWC instead of existing Aura Components?
- Better Performance : render faster than aura components
- More Standards, less proprietary : LWC has built-in browser security features from Web Components
Standards
- Easy to Learn: takes the form through native web standards, no added abstraction layer like Aura
Framework or any other framework, we only need standard JavaScript to develop
- Faster loading sites: is faster in loading the developed components than Aura Components and is
lightweight framework which is built on web standards
- Easier to ramp for developers : No additional framework is needed to learn in order to develop LWC and
hence transition for the developers is a lot easier.
- Better security, better testing and better browser compatibility: With LWC, CSS, Script and DOM
Isolation are better and has more limited event scope

PAGE 11
Coexistence and interoperability of AURA and LWC
- Aura components and Lightning web components can coexist on the same page
- Aura components can include Lightning web components
- Aura components and Lightning web components share the same base Lightning components.
- Aura components and Lightning web components share the same underlying services (Lightning Data
Service, User Interface API, etc.).

PAGE 12
Supported browsers for salesforce LWC

PAGE 13
Supported Javascript for salesforce LWC
Lightning Web Components JavaScript support includes
- ES6 (ECMAScript 2015)
- ES7 (ECMAScript 2016)
- ES8 (ECMAScript 2017)—excluding Shared Memory and Atomics
- ES9 (ECMAScript 2018)—including only Object Spread Properties (not Object Rest Properties)

PAGE 14
Supported Salesforce Experience and tools
- Custom Tabs
- Lightning Experience - Utility Bars
- Salesforce App - Flows
- Lightning Communities - Embedded Service Chat
- Lightning App Builder - Gmail and Outlook integration
- Experience Builder - Unlocked Packages
- Standalone Apps - Unmanaged Packages
- Lightning Components for Visualforce - Change Sets
- Lightning Out - Metadata API—LightningComponentBundle
- Tooling API—LightningComponentBundle,
LightningComponentResource

PAGE 15
Set up development environment for lightning web component
➢ Sign up for salesforce Account (if does not have)
➢ Enable My Domain in Your Development Org
➢ Enable Debug Mode in Your Development Org
➢ Install a Code Editor
➢ Visual studio code
➢ Salesforce Extension Pack
➢ Set Up Linting
➢ Install the Salesforce CLI
➢ SFDX Commands

PAGE 16
Enable My Domain
➢ to better manage login and authentication
➢ can include your company name in your URL
➢ customize your login page, change the color scheme, add your own content on the right side of the
login page
➢ Work in multiple Salesforce orgs at the same time
➢ Set custom login policy to determine how users are authenticated
My Domain is required to use many Salesforce features, including
➢ Single sign-on (SSO) with external identity providers
➢ Social sign-on with authentication providers, such as Google and Facebook
➢ Lightning components in Lightning component tabs, Lightning pages, the Lightning App Builder, or
standalone apps

PAGE 17
Enable Debug Mode
➢ enable debug mode To make it easier to debug JavaScript code
➢ framework JavaScript code isn’t minified and easier to read and debug.
➢ Only enable debug mode for users who are actively developing or debugging JavaScript.
Setup ➔ Debug Mode ➔ Locate User and Enable it

PAGE 18
Install Code Editor
➢ Install a Code Editor
➢ Visual studio code https://code.visualstudio.com/
➢ Salesforce Extension Pack https://marketplace.visualstudio.com/items?itemName=salesforce.salesforcedx-
vscode

PAGE 19
Install Salesforce CLI
➢ Access all salesforce tools https://developer.salesforce.com/tools
➢ Install Salesforce CLI - is a powerful command line interface that simplifies development and build automation when
working with your Salesforce organization
➢ Set and verify path for CLI

PAGE 20
Setup DevHub and Scratch Org
DevHub: Main salesforce org that create and manage scratch org
Enable Devhub Setup➔Dev Hub➔Enable
Authorize dev hub :
1- Sfdx: authorize dev hub
2- sfdx force:auth:web:login -d -a LWC -HUB

Scratch Org:
- are temporary Salesforce Orgs where developers will build source code and configure an application
- Is fully configurable allowing developers to emulate different editions with different feature
- Source driven and disposable deployment of salesforce code and metadata
- sfdx create a default scratch org
- sfdx open default org

PAGE 21
Scratch Org VS Sandbox
- Scratch Org do not replaces Sandboxes
- Scratch org are not permanent and they don't include any production data
- Scratch orgs compliment sandboxes

PAGE 22
Create Lightning Web Component and Its Folder Structure

- Is a reusable custom HTML element with its own API.


- Must include an HTML file, a javascript file and a metadata configuration file
- Files must use the same name
- Use sfdx: create lightning web component

- Folder: componentName
- componentName.html
- componentName.Js
- componentName.js-meta.xml
- componentName.css
- componentName.svg

PAGE 23
Folder and File Naming Conventions
 Must begin with a lowercase letter
 Must contain only alphanumeric or underscore characters
 Must be unique in the namespace
 Can’t include whitespace
 Can’t end with an underscore
 Can’t contain two consecutive underscores
 Can’t contain a hyphen (dash)

When refer child component in parent:


child componentName : myChildComponent
can be refered in parent as c-my-child-component

PAGE 24
Component Files
HTML File
-Naming convention is componentName.HTML
- should have root tag as <template>
JavaScript File
Every UI component must include a JavaScript file with at least this code.
Naming convention pascal case.

- LightningElement is a custom wrapper of the standard HTML element

PAGE 25
Component Files
Configuration file
- defines the metadata values for the component
- <component>.js-meta.xml

- apiVersion -masterLabel : title of the component


- Description - Targets : where the component can be added
- Target = lightning__AppPage, lightning__HomePage, lightning__RecordPage,
- isExposed lightning__UtilityBar, lightning__UtilityBar, lightning__FlowScreen,
lightning__Tab, lightning__Inbox, lightningCommunity__Page,
lightningCommunity__Default
- targetConfigs and targetConfig:
PAGE 26
Component Configuration Files
Configuration file

PAGE 27
Component test

PAGE 28
Component CSS Files
- Use standard CSS syntax to style Lightning web components
- Use Lightning Design system to style lightning web component
- Naming convention myComponent.css
- A component can include one css file
- Each component can have only one style sheet
- Component can not share the style sheet
different way you can apply styles to lightning web components
- Using Lightning Design System
- Custom CSS style sheet
- Style the host element
- Using Aura design token
* A parent can’t reach into a child to style elements inside its shadow DOM

PAGE 29
Style Using Lightning Design system
- includes the resources to create user interfaces consistent with the Salesforce Lightning principles, design
language, and best practices
- automatically included for Lightning Components running in the Lightning Experience and Salesforce S1
mobile application

PAGE 30
Style the Host Element
- use the standard :host selector to style the host element
- can select a custom element from inside its shadow DOM
- only if the selector given as the function's parameter matches the shadow host
- CSS styles applied to the host element don’t affect child components or parent components
- To style the host element, use the :host selector.

PAGE 31
Fields, Properties and Attributes
- Field and property are interchangeable term
- In JavaScript referred as property and in HTML refered as attribute
- Property names in JavaScript are in camel case while HTML attribute names are in kebab case
- All fields in a Lightning web component class are reactive
- Public properties are reactive. Decorate with @api
- field contains a primitive data type are reactive
- Object created with {} and annonated with @track are reactive
- Arrays created with [] and annonated with @track are recative

PAGE 32
Property and Attribute Names
- Property names in JavaScript are in camel case while HTML attribute names are in kebab case
- Ex: Javascript property: courseName same in html attribute refer as course-name
- Do not use a leading uppercase character in a public property name because HTML attributes in a template
cannot contain uppercase characters
- Ex: donot use @api CourseName as propertyname\
- Don’t start a property name with on,aria,data
- Don’t use reserved words as property name – slot,part,is

PAGE 33
Public Properties
- Property names in JavaScript are in camel case while HTML attribute names are in kebab case
- Public properties are reactive
- Import @api decorator from lwc

PAGE 34
Public Properties
- owner component that uses a component in its markup can access the component’s public properties via
DOM properties.

PAGE 35
Conditional Render using if:true
- Using if:true|false directive to nested <template> tag.

PAGE 36
How to Iterate multiple items in LWC
- Using for:each directive or the iterator directive to iterate over collection
- Must use a key directive to assign a unique Id to each item. Key is used for performance optimization and
not reflected in DOM

PAGE 37
How to Iterate multiple items in LWC
Use of iterator directive gives control to add special behaviors on first and last element
Properties of iterator:
value – items in the list
index- index of the item in the list
first – Boolean indicating first element of the collection
last – Boolean indicating last element of the collection

PAGE 38
How to fetch Inputs in Lightning Web Components

- Using property
- Using getters
- Using querySelector
- Using querySelectorAll

PAGE 39
Component Composition

- Using property
- Using getters
- Using querySelector
- Using querySelectorAll

PAGE 40
Access Custom Label in LWC
- Custom labels are custom text values
- can create up to 5,000 custom labels for your organization, and
they can be up to 1,000 characters in length
- Import labels from the @salesforce/label

PAGE 41
Access Static Resource in LWC
- Static resources allow you to upload content that you can
reference in a Visualforce page, Aura, apex,LWC.
- Resources can be archives (such as .zip and .jar files), images,
stylesheets, JavaScript, and other files.
- Import static resources from the @salesforce/resourceURL

PAGE 42
Access Current user information in LWC
- Import id / isGuest from the @salesforce/user

PAGE 43
LWC Navigation services
- Use navigation service ‘lightning/navigation’ To Navigate in LEX, Lightning communities, salesforce app
- Navigation service uses a pagereference instead of URL.
- Pagerefrence is a Javascript object describing pageType,its attributes and the state of the page
- Lightning navigation not supported in lightning out or lightning component for visualforce
1- Navigate to object Home
2- Navigate to list view
3- Navigate to New Record
4- Navigate to View Record
5- Navigate to edit record
6- Navigate to related list
7- Navigate to Tab
8- Navigate to files Home
9- Navigate to chatter

PAGE 44
How to use Lightning navigation?
Step1
import lightning/navigation

Step2
Apply NavigationMixin function in component base class / Extend NavigationMixin in Javascript class

Step 3
Create Javascript pageReference object – describing page type, its attribute and state of the page

Step 4
Dispatch/Fire the navigation service – [NavigationMixin.Navigate](pageReference,[replace])
Note: If you are navigating to Lightning Component from LWC, you need to implement
the lightning:isUrlAddressable interface in your Lightning Component PAGE 45
How to use Lightning navigation?

navigation service adds two APIs to your component's class


Navigate: to navigate to another page in the application
[NavigationMixin.Navigate](pageReference, [replace])
GenerateUrl : to get a promise that resolves to the resulting URL
[NavigationMixin.GenerateUrl](pageReference)

PAGE 46
Lightning navigation to Object Home
Type:
Standard__objectPage
Attributes:
actionName: home – is a required attribute
objectApiName: Api name of standard/custom object

PAGE 47
Lightning navigation to Object Home
Type:
Standard__objectPage
Attributes:
actionName: home – is a required attribute
objectApiName: Api name of standard/custom object

PAGE 48
Lightning navigation to Object list view
Type:
Standard__objectPage
Attributes:
actionName: home – is a required attribute
objectApiName: Api name of standard/custom object

PAGE 49
Lightning navigation to New Record Page
Type:
Standard__objectPage
Attributes:
actionName: new – is a required attribute
objectApiName: Api name of standard/custom object

PAGE 50
Lightning navigation to View/Edit Record Page
Type:
Standard__recordPage
Attributes:
actionName: view – is for viewing the record/ edit is for editing the record
objectApiName: Api name of standard/custom object

PAGE 51
Lightning navigation to Web page type
Type:
Standard__webPage
Attributes:
url: url of the page to navigate

PAGE 52
Lightning navigation to Chatter
Type:
Standard__webPage
Attributes:
url: url of the page to navigate

PAGE 53
How to access salesforce Data in LWC?
- Use Lightning Data Service to access salesforce data
- Use Base Lightning Component to Work with salesforce records
- Use Wire service to Get Salesforce Data
- Use Apex Methods in LWC
- Use API from Apex
- Use of Continuation to make long running call outs

PAGE 54
How to Use Apex to access salesforce Data
Step1:
Import methods from apex classes into javascript classes using ES6 import
import apexMethod from ‘@salesforce/apex/Namespace.className.ApexMethodName’;
Step 2:
- Call apex methods as functions into component by calling either via the Wire service or imperatively
- Three way to call apex method
1- Wire a Property
2- Wire a Function
3- call a method imperatively
- Apex Method must be static and either global or public and Annonated with @AuraEnabled

PAGE 55
How to Use Apex to access salesforce Data
What type of Apex class /Method can be used in LWC?
- Method must be Static
- Method must be either global or public
- Must be annotated with @AuraEnabled
What Parameter can be used in Method?
- supported parameter are
- Primitive
-subject (standard/custom)
- Apex
- collection

PAGE 56
How to Use Apex to access salesforce Data
Client side caching
- Use @AuraEnabled(cacheable=true)
- method must only get data and can not change the data
- use refreshApex() to query server for updated data and refresh cache

PAGE 57
How to Use Apex to access salesforce Data
Apex Wire Method to Property:
step1
Import apex method to Javascript class
* Method annotated with @AuraEnabled(cacheable=true)
step2
use wire service @wire to a javascript property using below syntax

* @wire decorated property returns result to data/error property

PAGE 58
How to Use Apex to access salesforce Data
Apex Wire Method to Property/Function:With Dynamic Input
step1
Import apex method to Javascript class
* Method annotated with @AuraEnabled(cacheable=true)
step2
use wire service @wire to a javascript property/Function using below syntax

* @wire decorated property returns result to data/error property

PAGE 59
How to Use Apex to access salesforce Data
Lets Practice: Apex Wire Method to Property/Function:With Dynamic Input

PAGE 60
How to Use Apex to access salesforce Data
Lets Practice : Apex Wire Method to Property

PAGE 61
How to Use Apex to access salesforce Data
Apex Wire Method to Function:
step1
Import apex method to Javascript class
* Method annotated with @AuraEnabled(cacheable=true)
step2
use wire service @wire to a javascript property using below syntax

* @wire decorated property returns result to data/error property

PAGE 62
How to Use Apex to access salesforce Data
Lets Practice:Apex Wire Method to Function

PAGE 63
How to Use Apex to access salesforce Data
Call an Apex Method Imperatively
- To call a method not annotated with cacheable=true
- Can perform DML too
- Control when the invocation occurs
- Can work with objects not supported by User interface API( task,event etc)
- https://developer.salesforce.com/docs/atlas.en-us.uiapi.meta/uiapi/ui_api_get_started_supported_objects.htm
- To call method from javascript that not extends LightningElement

PAGE 64
How to Use Apex to access salesforce Data
Call an Apex Method Imperatively

Syntax:

PAGE 65
How to Use Apex to access salesforce Data
Lets practice: Call an Apex Method Imperatively

PAGE 66
How to access salesforce Data in LWC?
- Use Lightning Data Service to access salesforce data
- Use Base Lightning Component to Work with salesforce records
- Use Wire service to Get Salesforce Data
- Use Apex Methods in LWC
- Use API from Apex
- Use of Continuation to make long running call outs

PAGE 67
Lightning Data service
• No SOQL, No Apex, No DML
• Supported objects with User Interface API
• Cached and shared across the component
• Use Wire adapter and functions in the lightning/ui*Api modules
• Powers base component
• Lightning-record-edit-form
• Lightning-record-form
• Lightning-record-view-form

• Respects CRUD, FLS and sharing

PAGE 68
Lightning Data service
LDS
(Base Component/Wire
adapter)

Supported UI API

LWC 1 – View the data –Refresh Database


LDS

LWC2 – update the data

Lightning Web Component


Apex
Name Rating Type

PAGE 69
Work With Record Using Base Component

- Create a record Customize Form layout/predefined field

- Load a record
Customize Form layout

- Edit a Record
Customize Form layout/predefined field

PAGE 70
Work With Record Using Base Component
- Create a record

- Do not specify record-id attribute


- Mode=“edit” by default
- Specify layout-type/field attribute

* Implement LDS , Not Required Apex to create, take care FLS and sharing

PAGE 71
Work With Record Using Base Component
- Create a record

- Customize Form layout, Predefined field values


- Custom rendering of data
- editable fields=>lightning-input-field
- read-only=>lightning-output-field
- Handles field level validation error and LDS errors automatically
- Lightning-message to display error message
- Doesn’t provide own Cancel and Save button
- To reset form field use reset()
- Event: error,load,submit,success

* Implement LDS , Not Required Apex to create, take care FLS and sharing

PAGE 72
Work With Record Using Base Component
- View a record

- Mode:
- View :outfield with inline editing
- Read-only : only output field

* Implement LDS , Not Required Apex to create, take care FLS and sharing

PAGE 73
Work With Record Using Base Component
- View a record

- Display record with custom layout


- Use Lightning-output-field
* Implement LDS , Not Required Apex to create, take care FLS and sharing

PAGE 74
Work With Record Using Base Component
- Edit a record

- Use record-id and object-api-name


- Mode=edit
- Edit Record

- To provide custom layout


* Implement LDS , Not Required Apex to create, take care FLS and sharing

PAGE 75
How to Show Toast Notification?
Popup to alert users of a success/error/warning/information.

create and dispatch a ShowToastEvent with


- title
-message
- Variant =>success/error/warning/info
- mode
Syntax:

PAGE 76
@Salesforce Modules
Add functionality to LWC in runtime
- @salesforce/apex => import apex method

- @salesforce/apexContinuation =>make long running callouts

@salesforce/client/formfactor – large,medium,small
@salesforce/contentAssetURL => import content asset file

@salesforce/i18n => import internationalization properties

PAGE 77
@Salesforce Modules
Add functionality to LWC in runtime
@salesforce/client/formfactor – large,medium,small

@salesforce/contentAssetURL => import content asset file

@salesforce/i18n => import internationalization properties

PAGE 78
@Salesforce Modules
Add functionality to LWC in runtime
@salesforce/schema => import reference to Salesforce object and fields

PAGE 79
@Salesforce Modules
Add functionality to LWC in runtime
@salesforce/User => import current user id

PAGE 80
@Salesforce Modules
Add functionality to LWC in runtime
@salesforce/resourceURL => import static resource to LWC

@salesforce/label =➔import salesforce label

PAGE 81
Use wire service adapter to access data
- Use LDS wire adapter with @wire in Javascript class
- Built on top of User interface API and available in lightning/ui*Api module
- Immutable stream of data to the component
- Dynamic binding with $
- Terminology – request/fetches=>provision
Steps:
Step1: import adapter to Javascript class

Step2: use wire service to use adapter

PAGE 82
Use wire service adapter to access data
- Use LDS wire adapter with @wire in Javascript class
- Built on top of User interface API and available in lightning/ui*Api module
- Immutable stream of data to the component
- Dynamic binding with $
- Terminology – request/fetches=>provision
Steps:
Step1: import adapter to Javascript class

Step2: use wire service to use adapter

PAGE 83
Use wire service adapter to access data
Different Adapter:

PAGE 84
Use wire service adapter to access data
Different Adapter:

Step1:

Step2:

PAGE 85
Use wire service adapter to access data
Different Adapter:

Step1:

Step2:

PAGE 86
Use wire service adapter to access data
Different Adapter:getRecord

PAGE 87
COMPONENT COMMUNICATION THROUGH EVENTS
1- Communication using Method in LWC (Parent to child)
2- Custom event Communication in LWC (Child to Parent)
3- Publish Subscriber model in LWC ( Components not related)

PAGE 88
COMPONENT COMMUNICATION USING METHOD (Parent to child)

From Parent comp A to


child Comp B

From Parent comp B to


child Comp E

From Parent comp E to


child Comp F

PAGE 89
COMPONENT COMMUNICATION USING METHOD (Parent to child)

Step 1:
Create a public properties/method in child component which will be available to parent
use @api
Step 2:
- Find child component in parent
- Access child method/properties in parent component

PAGE 90
COMPONENT COMMUNICATION USING METHOD (Parent to child)

PAGE 91
Custom Event Communication(Child to Parent)
-custom event to communicate from child to parent

PAGE 92
Custom Event Communication(Child to Parent)

DOM Event includes


- event name
- configuration to initialize event
- Javascript object that emits the event
Step 1: Create Event
Step 2: Dispatch Event
Step 3: Handle Event
Step 4: Event propagation

PAGE 93
Custom Event Communication(Child to Parent)
Step 1: Create Event
- Use CustomEvent() constructor to create an event . Pass custom event name and detail of the event
- Event Name:
- No Uppercase letter, No spaces, No underscores to separate words
- Do not prefix event name with string on

Syntax:

Step 2: Dispatch Event


Dispatch event with

Pass data in event


- Set a detail property in the customEvent constructor

PAGE 94
Custom Event Communication(Child to Parent)
Step 3: Handle event
2 ways to listen event
- declarative via html markup
* declare the listener in markup in the template of owner component
* define the handler function in the javascript file
- javascript using addEventListener method
* define both listener and the handler function in javascript file

Event Propagation:
event bubbling and event capturing
bubbles: true/false
composed: true/false

PAGE 95
Custom Event Communication(Child to Parent)

declarative via html markup

PAGE 96
Communicate Between Components(not in the same DOM TREE)
- Publish subscriber pattern
- Components on a single page
- Lightning message channel
- Within a single lightning page or across multiple pages
- Works between LWC, AURA and VF pages

PAGE 97
Communicate Between Components(not in the same DOM TREE)
- Publish subscriber pattern
- One component publishes an event
- Another component subscribe to receive and handle the event
- Every component that subscribes the event will receive the event

Component 1 Component 2

Publisher Subscriber

PAGE 98
[email protected]
Email Id

Email Message

Enter your email body here and send

Send

PAGE 99

You might also like