- Introduction to LWC
- Websites to Bookmark
- Prerequisites
- VS Code and SFDX Basics
- Choose between LWC or Aura
Comparison of Lightning Web Components (LWC) and Aura Components
Aspect Lightning Web Components (LWC) Aura Components Technology Based on modern web standards (e.g., Web Components, ES6+). Built on Salesforce's proprietary framework. Performance Generally faster due to optimized rendering and smaller JavaScript footprint. Can be slower due to additional overhead and rendering complexities. Learning Curve Easier for developers familiar with standard web technologies (HTML, CSS, JavaScript). Requires learning Salesforce-specific framework and conventions. Component Model Uses a simple and modern model with custom elements and shadow DOM. Uses a more complex model with extensive configuration and event handling. Data Binding Supports reactive data binding and property change detection. Uses a more complex approach with aura:attribute and change handlers. Event Handling Utilizes standard DOM events and custom events. Uses Aura-specific event system with component events and application events. Security Enhanced security features, including Locker Service for strict security controls. Includes Locker Service but historically had more security concerns. Dependency Management Better dependency management through import statements and modules. Uses aura:dependency and global controllers, which can be less efficient. Lifecycle Hooks Provides modern lifecycle hooks such as connectedCallback, disconnectedCallback. Offers specific lifecycle methods like init, render, afterRender. Data Access Utilizes the Lightning Data Service and standard Apex for data access. Uses force:recordData, aura:attribute, and direct Apex calls. Component Communication Supports a straightforward approach with pub/sub model and @api decorators. Uses a more complex approach with events, attributes, and application-level communication. Debugging Modern debugging tools compatible with standard web development tools. Requires Salesforce-specific tools and can be more challenging to debug. Browser Support Supported on modern browsers and optimized for performance. Supported on older browsers but can be less optimized for newer ones.
- Calculator Project
- Data Binding
In Lightning Web Components (LWC), data binding is a mechanism that synchronizes the data between the component's JavaScript code and its HTML template. It allows the component to dynamically update the UI based on changes in the underlying data and vice versa.
Here’s a detailed breakdown of how data binding works in LWC:
Different ways of data binding
There are two way to data binding in LWC.
- Using Expressions
- Using getter properties
1. One-Way Data Binding
One-way data binding means that the data flows in one direction - from the JavaScript controller to the HTML template. This type of binding is useful for displaying data that doesn't need to be modified by the user.
Example of One-Way Data Binding
- In VS Code, open the Command Palette by pressing
Ctrl+Shift+P
on Windows orCmd+Shift+P
on macOS. - Type
SFDX
and SelectSFDX: Create Lightning Web Component.
- Type
dataBinding
as the name of the new component and pressEnter.
- Again, Press
Enter
to accept the defaultforce-app/main/default/lwc.
- Goto your
lwc
folder, you will see one new component with the namedataBinding
gets created. - Let's add the following code to
dataBinding.html
,dataBinding.js
anddataBinding.js-meta.xml
dataBinding.html<template> <lightning-card title="One-way Data Binding Demo" icon-name="custom:custom1"> <hr /> <div class="slds-p-around_medium"> <h1>My full name is {fullname}</h1> </div> </lightning-card> </template>
- Inside the
<template>
, we have used thelightning-card
- Inside the
lightning-card
We have created a<h1>
tag with text and propertyfullname
binding. {fullname}
- To bind a property in a template we have to surround the property with curly braces:
dataBinding.js
import { LightningElement } from "lwc"; export default class DataBinding extends LightningElement { fullname = "Learning passional"; }
- In the first line, we are importing
LightningElement
fromlwc
module - After that, we are creating a
class
DataBinding
(Note - the class name always be pascal case) - Within the
class
, we have to define a propertyfullname
and assign a valueLearning passional
to it. - So when a component loads, it initialize the variable
fullname
with valueLearning passional
. After that, when HTML starts rendering in the browser, lwc engine looks for the{}
tags and replace thefullname
inside the curly braces with the properties defined inside the classDataBinding
.
dataBinding.js-meta.xml
<?xml version="1.0" encoding="UTF-8"?> <LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata" fqn="dataBinding"> <apiVersion>46.0</apiVersion> <isExposed>true</isExposed> <targets> <target>lightning__AppPage</target> <target>lightning__RecordPage</target> <target>lightning__HomePage</target> </targets> </LightningComponentBundle>
dataBinding.js-meta.xml
is a configuration file- The configuration file defines the metadata values for the component, including the design configuration for Lightning App Builder and Experience Builder.
- This file only show your component in app builder
2. Two-Way Data Binding
Two-way data binding allows for the synchronization of data between the UI and the component's JavaScript. When the data changes in the UI (e.g., user input), the changes are automatically propagated to the JavaScript, and vice versa.
How to achieve Two-Way Data Binding?
- The Lightning Web Components programming model has given us some decorators that add functionality to property or function.
- @track is the decorator that helps us to track a private property's value and re-render a component when it changes.
- Tracked properties are also called private reactive properties.
@track
helps us to achieve two-way data binding
Example of Two-Way Data Binding
- In VS Code, open the Command Palette by pressing
Ctrl+Shift+P
on Windows orCtrl+Shift+P
on macOS. - Type
SFDX
and SelectSFDX: Create Lightning Web Component.
- Type
twoWayDataBinding
as the name of the new component and pressEnter.
- Again, Press
Enter
to accept the defaultforce-app/main/default/lwc.
- Goto your
lwc
folder, you will see one new component with the nametwoWayDataBinding
gets created. - Let's add the following code to
twoWayDataBinding.html
,twoWayDataBinding.js
andtwoWayDataBinding.js-meta.xml
twoWayDataBinding.html
<template> <lightning-card title="Two-way Data Binding Demo" icon-name="custom:custom2"> <hr /> <!--First input box--> <div class="slds-p-around_medium"> <lightning-input type="text" name="fullname" label="Enter your name:" onkeyup={changeHandler} value={fullname} ></lightning-input> </div> <!--Second input box--> <div class="slds-p-around_medium"> <lightning-input type="text" name="title" label="Enter your title:" onkeyup={changeHandler} value={title} ></lightning-input> </div> <!--Result of binding--> <div class="slds-p-around_medium"> <h5>My name is {fullname} and my title is {title}</h5> </div> </lightning-card> </template>
- we have created two input box
fullname
andtitle
usinglightning-input
inside thelightning-card
. {name}
- is used to bindfullname
property tofullname
input box{title}
- is used to bindtitle
property totitle
input box- we have defined an event handler called
onKeyUp
that is bind tochangeHandler
, which gets triggered on every key up. - We have used the
<h5>
tag to test the two-way data binding
twoWayDataBinding.js
import { LightningElement, track } from "lwc"; export default class TwoWayDataBinding extends LightningElement { @track fullname = "Learning passional"; @track title = "Salesforce developer"; changeHandler(event) { this[event.target.name] = event.target.value; } }
- In the first line, we are importing
LightningElement
andtrack
fromlwc
module - After that, we are creating a
class
TwoWayDataBinding
(Note - the class name always be pascal case) - Within the
class
, we have to define two propertiesfullname
andtitle
. @track
decorator decorates both properties.- Both properties are assigned with an initial value of
Salesforce Troop
andSalesforce developer
, respectively. - We have defined a method
changeHandler
that takes the value from the textbox and update the property based on the input box name
twoWayDataBinding.js-meta.xml
<?xml version="1.0" encoding="UTF-8"?> <LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata" fqn="twoWayDataBinding"> <apiVersion>46.0</apiVersion> <isExposed>true</isExposed> <targets> <target>lightning__AppPage</target> <target>lightning__RecordPage</target> <target>lightning__HomePage</target> </targets> </LightningComponentBundle>
dataBinding.js-meta.xml
is a configuration file- The configuration file defines the metadata values for the component, including the design configuration for Lightning App Builder and Experience Builder.
Observe the Properties of an Object or the Elements of an Array
There is still a scenario where @track is useful. When a field holds an object or an array, there is a limit to the depth of changes that are monitored. To instruct the framework to observe modifications to an object's properties or an array's elements, apply the @track decorator to the field.
In the absence of @track, the framework monitors changes that involve assigning a new value to a field. If the new value is not === to the previous value, the component will be re-rendered.
For example, let's define the fullName field, which consists of an object with two properties, firstName and lastName.
fullName = { firstName : '', lastName : '' };
The framework monitors changes that involve assigning a new value to fullName. The following code assigns a new value to the fullName field, triggering a re-render of the component.// Component re-renders.
this.fullName = { firstName : 'Mark', lastName : 'Doe' };
However, if we assign a new value to one of the object's properties, the component will not re-render because the properties are not being observed.// Component does not re-render.
this.fullName.firstName = 'Mark';
The framework monitors changes that involve assigning a new value to the fullName field. The provided code does not do that; instead, it assigns a new value to the firstName property of the fullName object.To instruct the framework to observe changes to the object's properties, decorate the fullName field with @track. Now, if we modify either property, the component will re-render.
// Component re-renders.
@track fullName = { firstName : '', lastName : '' };
this.fullName.firstName = 'Mark'; - Type of Decorators in Lightning Web Component
Lightning Web Components (LWC), decorators are special functions that can modify properties, methods, or classes. They provide a way to add metadata to elements in your component and enhance their behavior.
LWC primarily uses three decorators:- @api
- @track
- @wire
1. @api
- decorator in Lightning Web Components (LWC) is used to expose a public property in a component. This allows parent components or other parts of the application to interact with and set values
- Public properties define API of a component whereas public methods are part of a component’s API
- A Component is re-rendered when the value of a referenced public property is modified or changed
- To pass data from parent component to child component, @api decorator in the child component exposes a property by making it public so that parent component can update it
- @api properties can be exposed in an App builder.
- The
@api
decorator in Lightning Web Components (LWC) is used to expose public properties and methods. These properties and methods can be accessed and modified by parent components, allowing for better encapsulation and component reusability.
Usage
1. Public Properties
Public properties are accessible from the parent component's markup or JavaScript. By using the
Example: Exposing a Property@api
decorator, you can expose a property to make it configurable or readable by the parent component.javascript
// childComponent.js import { LightningElement, api } from 'lwc'; export default class ChildComponent extends LightningElement { @api message = 'Hello, World!'; }
html
<!-- parentComponent.html -->
<template> <c-child-component message="Hello, Parent!"></c-child-component> </template>
- In this example, the
Usage:message
property inChildComponent
is exposed and set from theparentComponent
.- Setting Properties: A parent component can set the value of a public property in the child component.
- Getting Properties: The parent component can read the value of a public property of the child component.
2. Public Methods
- Public methods allow the parent component to invoke functions defined in the child component. These methods are decorated with
@api
to make them accessible.- Example: Exposing a Method
javascript
// childComponent.js import { LightningElement, api } from 'lwc'; export default class ChildComponent extends LightningElement { @api publicMethod( ) { console.log('Public method called'); } }
javascript
// parentComponent.js import { LightningElement } from 'lwc'; export default class ParentComponent extends LightningElement { callChildMethod( ) { this.template.querySelector('c-child-component').publicMethod(); } }
html
<!-- parentComponent.html --> <template> <c-child-component></c-child-component> <button onclick={callChildMethod}>Call Child Method</button> </template>
- In this example, the
publicMethod
inChildComponent
can be called from theParentComponent
by usingquerySelector
.- Usage:
- Invoking Methods: A parent component can call public methods on the child component to perform actions or trigger behavior in the child component.Best Practices
- Encapsulation: Use
@api
to expose only those properties and methods that are necessary for the parent component to interact with the child component. This maintains encapsulation and hides implementation details.- Consistent Naming: Name public properties and methods clearly to indicate their purpose and usage.
- Validation: When exposing properties, ensure they have appropriate validation and defaults to handle incorrect or missing values from the parent component.
2. @track : Tracking Private Reactive Properties
The
@track
decorator in Lightning Web Components (LWC) is used to make properties reactive. When a tracked property's value changes, the component re-renders to reflect the updated value. This is particularly useful for ensuring the UI updates in response to changes in component state.- To expose a private property or a private method, declare with @track. Also known as Private reactive properties
- To track a private property and to re-render component when that property changes, use @track decorator (Available only for the component where it is declared)
- Fields which are using @track decorator that contains an object or an array, tells the framework to observe changes to the properties of an object or elements of an array
- After Salesforce Spring ’20, all the fields in a Lightning Web Component are reactive. If a field is used in a template & value changes, the component re-renders and displays a new value by default.
- Key Features: Deep Tracking: While LWC natively observes changes to properties, @track offers a deeper level of observation, specifically for nested properties inside objects or arrays.
Best Practices
- Use for Simple Properties: Use
@track
for simple properties or objects where you need the component to react to changes. - Reassign Objects for Reactivity: When dealing with objects, ensure you reassign the entire object to trigger reactivity.
- Avoid Overusing: Use
@track
judiciously. Overusing tracked properties can lead to performance issues, especially with large or deeply nested objects.
Alternatives to
@track
In many cases, you might not need the
@track
decorator if the reactivity is achieved through other means. For example, if a property is public and updated by a parent component, using@api
may be sufficient.Additionally, if your component uses complex state management or reactive frameworks, you might handle state changes differently, often without needing
@track
.Explanation and Usage
Reactive Properties with
@track
When you decorate a property with
@track
, any changes to that property's value will automatically trigger a re-render of the component. This is especially useful for simple properties and objects.Basic Example:
javascript
// myComponent.js import { LightningElement, track } from 'lwc'; export default class MyComponent extends LightningElement { @track message = 'Hello, World!'; updateMessage() { this.message = 'Hello, LWC!'; } }
html
<!-- myComponent.html --> <template> <p>{message}</p> <button onclick={updateMessage}>Update Message</button> </template>
In this example, when the
updateMessage
method is called, themessage
property is updated and the component re-renders to display the new message.Tracking Objects
When tracking objects, changes to the properties of the object are tracked, but you need to reassign the entire object to ensure reactivity.
Example:
javascript
// myComponent.js import { LightningElement, track } from 'lwc'; export default class MyComponent extends LightningElement { @track person = { firstName: 'John', lastName: 'Doe' }; updatePerson() { this.person.firstName = 'Jane'; this.person = { ...this.person }; // Reassign to ensure reactivity } }
html
<!-- myComponent.html --> <template> <p>{person.firstName} {person.lastName}</p> <button onclick={updatePerson}>Update Name</button> </template>
In this example, modifying the
firstName
property alone does not trigger reactivity. By reassigning theperson
object using the spread operator, the component re-renders to reflect the changes.3. The @wire Decorator: Leveraging Reactive Data Fetching
The
@wire
decorator in Lightning Web Components (LWC) is used to connect a property or method to a wire adapter. Wire adapters are functions provided by the Lightning Data Service or other sources that allow you to fetch and manage data in LWC. The wire service provisions the data to the property or method and keeps it up-to-date.The @wire decorator is used to read Salesforce data and leverage reactive data fetching in Lightning Web Components. By using @wire in the JavaScript class, a component can specify a wire adaptor or an Apex method to fetch data from Salesforce. When the wire service provisions the data, the component automatically rerenders to reflect the new data. This section will provide insights into the power and implementation considerations of using @wire in Lightning Web Components.
Key Features:
- Data Binding: @wire connects your component to Salesforce’s vast data repositories, whether they are object records, custom Apex methods, or other data sources.
- Reactivity: When the underlying data changes, the component updates, ensuring real-time data representation.
- Parameters: You can use dynamic parameters with @wire, which re-evaluates when those parameters change.
- Explanation and Usage The
@wire
decorator simplifies data fetching and makes it reactive, meaning that the component re-renders whenever the data changes. The wire service can be used to fetch data from Salesforce objects, call Apex methods, and more.
Syntax:
import <methodName> from ‘@salesforce/apex/<Namespace.ApexClassName.apexMethod>’;
@wire(methodName, {methodParams})
propertyOrFunction;
methodName: A variable that identifies the Apex method.
apexMethod: The name of the Apex method to import.
ApexClassName: The name of the Apex class.
Namespace: Defines the namespace of the Salesforce organization. Only specify a namespace when the organization doesn’t use the default namespace (c)
Best Practices
- Reactive Parameters:
- Use reactive parameters (e.g.,
$recordId
) to dynamically update the wire adapter's inputs when the parameter changes.
- Use reactive parameters (e.g.,
- Handle Data and Errors:
- Always handle both data and error states to ensure your component can gracefully handle any issues.
- Performance Considerations:
- Limit the number of wire adapters in a component to avoid performance issues. Fetch only the necessary data.
- Lazy Loading:
- For expensive or optional data operations, consider fetching data on-demand rather than wiring it to properties or methods.
Basic Usage of
@wire
1. Wiring to a Property
When wiring to a property, the wire adapter automatically provisions data to the property.
Example: Fetching a Record
javascript
// myComponent.js import { LightningElement, wire } from 'lwc'; import { getRecord } from 'lightning/uiRecordApi'; import ACCOUNT_NAME from '@salesforce/schema/Account.Name'; export default class MyComponent extends LightningElement { recordId = '001000000000000000'; // Example record ID @wire(getRecord, { recordId: '$recordId', fields: [ACCOUNT_NAME] }) account; get accountName() { return this.account.data ? this.account.data.fields.Name.value : ''; } }
html
<!-- myComponent.html --> <template> <template if:true={account.data}> <p>Account Name: {accountName}</p> </template> <template if:true={account.error}> <p>Error: {account.error}</p> </template> </template>
In this example, the
getRecord
wire adapter fetches an account record. Theaccount
property automatically receives the fetched data, and the template displays the account name.2. Wiring to a Method
When wiring to a method, the wire adapter provisions data to the method, which can then handle the data.
Example: Fetching a List of Records
javascript
// myComponent.js import { LightningElement, wire } from 'lwc'; import { getListUi } from 'lightning/uiListApi'; import ACCOUNT_OBJECT from '@salesforce/schema/Account'; export default class MyComponent extends LightningElement { @wire(getListUi, { objectApiName: ACCOUNT_OBJECT, istViewApiName: 'AllAccounts' }) wiredAccounts({ error, data }) { if (data) { this.accounts = data.records.records; } else if (error) { this.error = error; } } accounts; error; }
html
<!-- myComponent.html --> <template> <template if:true={accounts}> <template for:each={accounts} for:item="account"> <p key={account.id}>{account.fields.Name.value}</p> </template> </template> <template if:true={error}> <p>Error: {error}</p> </template> </template>
In this example, the
getListUi
wire adapter fetches a list of account records. ThewiredAccounts
method processes the data and sets theaccounts
property. - what is the differnet between @api and @track and @wire in Lwc?
In Lightning Web Components (LWC),
@api
,@track
, and@wire
are decorators used to define different types of properties and functions. Here’s a comparison in a tabular format:Decorator Purpose Usage Reactivity Example @api
Public property that can be accessed by parent components. Use for properties and methods that need to be accessible from the parent component. Automatically reactive. @api message;
@track
Private reactive property that tracks changes to primitive values or object properties. Use for properties whose changes should trigger a re-render of the component. Automatically reactive. @track record = {};
@wire
Property or function to receive data from a wire adapter (such as Apex, LDS, or an external API). Use for properties or methods that need data from an external source. Reactive to data changes. @wire(getContacts) contacts;
- What is the difference between @track and @Api in LWC?
Here’s a detailed comparison of
@track
and@api
in table format, incorporating the additional information you provided:Feature @track @api Reactivity Yes. Changes to the property automatically trigger a re-render of the component. No. Changes to the property do not automatically trigger a re-render of the component. Accessibility Internal to the component. External to the component. Use case Properties that change over time, such as user input or data fetched from a server. Properties that need to be shared between components or accessed from outside the component. Relations Private properties. Public properties. Reactivity Both @track
and@api
mark a property as reactive. If the property’s value changes, the component re-renders.Both @track
and@api
mark a property as reactive. If the property’s value changes, the component re-renders.Visibility Tracked properties are private. Properties decorated with @api
are public and can be set by another component.Best Practice Track a property only if you want the component to re-render when the property’s value changes. Use @api
to expose properties or methods as part of a component’s API.Restriction We can’t decorate a property with both @track
and@api
.We can’t decorate a property with both @track
and@api
.Public Methods N/A @api
can be used to expose public methods that can be called by owner and parent components.Fields Fields are reactive. If a field’s value changes, and the field is used in a template or getter, the component re-renders and displays the new value. Fields are reactive. If a field’s value changes, and the field is used in a template or getter, the component re-renders and displays the new value. Special Use Case When a field contains an object or array, there’s a limit to the depth of changes tracked. Use @track
to observe changes to the properties of an object or the elements of an array.N/A - Using CSS
- LWC Bundle
- Conditional Rendering
- Looping or Iteration
We have to render the same set of elements with the same styling with different data in the HTML. To solve this issue, we have template looping in the LWC.
To render a list of items, use for:each directive or the iterator directive to iterate over an array. Add the directive to a nested <template> tag that encloses the HTML elements you want to repeat. We can call it for loop in LWC.
The iterator directive has first and last properties that let you apply special behaviors to the first and last items in an array.
Regardless of which directive you use, you must use a key directive to assign a unique ID to each item. When a list changes, the framework uses the key to rerender only the item that changed. The key in the template is used for performance optimization and isn’t reflected in the DOM at run time.
There are two types of directives by which we can achieve template looping.
1. for:each
2. iterator
For:each template directives in LWC(Lightning Web Component)
When using the for:each directive, use for:item=”currentItem” to access the current item. This example doesn’t use it, but 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.
Below is the syntax of the
for:each
loop<template for:each={array} for:item="currentItem" for:index="index"> -----Here your repeatable template comes----- </template>
Sno. attributes Description 1. for:each={array} for:each
takes thearray
as an input2. for:item="currentItem" currentItem
is the value of the current element.currentItem
is an alias and can be anyname.for:item
holds thecurrentItem
.3. for:index="index" index
is the current element index in the array.for:index
holds theindex
In Lightning Web Components (LWC), the
for:each
directive is used to iterate over a list of items and render a block of HTML for each item. Thekey
attribute is used in conjunction withfor:each
to uniquely identify each item in the list.Importance of
key
infor:each
- Efficient Rendering: The
key
helps LWC efficiently render and re-render lists of items. By providing a unique identifier for each item, the framework can track and update only the items that have changed, rather than re-rendering the entire list. This improves performance. - Avoiding Reordering Issues: When the order of items in the list changes, the
key
ensures that the framework can correctly map each rendered item to its corresponding data. Without unique keys, reordering could cause incorrect updates and result in UI inconsistencies. - Optimized DOM Manipulation: The use of keys allows the framework to optimize DOM manipulation by minimizing the number of elements that need to be added, removed, or updated.
what is key and it's importance in the loop
- A
key
is a special string attribute you need to include to the first element inside the template when creating lists of elements. - Keys help the LWC engine identify which items have changed, are added, or are removed.
- The best way to pick a key is to use a string that uniquely identifies a list item among its siblings.
Note- The key must be a string or a number, it can't be an object. You can't use the index as a value for the key.
Example of
for:each
template looping- In VS Code, open the Command Palette by pressing
Ctrl+Shift+P
on Windows orCmd+Shift+P
on macOS. - Type
SFDX
and SelectSFDX: Create Lightning Web Component.
- Type
templateLoopingForEach
as the name of the new component and pressEnter.
- Again, Press
Enter
to accept the defaultforce-app/main/default/lwc.
- Goto your
lwc
folder, you will see one new component with the nametemplateLoopingForEach
gets created. - Create one more file inside the folder
templateLoopingForEach.css
for styling. - Let's add the following code to
templateLoopingForEach.html
,templateLoopingForEach.js
,templateLoopingForEach.css
andtemplateLoopingForEach.js-meta.xml
templateLoopingForEach.js
import { LightningElement } from "lwc"; export default class TemplateLoopingForEach extends LightningElement { carList = ["Ford", "Audi", "Maruti", "Hyundai", "Mercedes"]; programmingList = [ { id: "06868", language: "HTML" }, { id: "19797", language: "CSS" }, { id: "298789", language: "Javascript" }, { id: "398798", language: "Apex" }, { id: "48967", language: "Aura" }, { id: "58798", language: "Java" } ]; }
templateLoopingForEach.html
<template> <!-- Card for for:each demo with an array --> <lightning-card title="for:each demo with array" icon-name="custom:custom14"> <ul class="slds-m-around_medium"> <template for:each={carList} for:item="car"> <a href="#" class="list-group-item list-group-item-action" key={car} >{car}</a > </template> </ul> </lightning-card> <hr /> <!-- Card for for:each demo with an array of objects --> <lightning-card title="for:each demo with array of objects" icon-name="custom:custom14" > <ul class="slds-m-around_medium"> <template for:each={programmingList} for:item="program"> <a href="#" class="list-group-item list-group-item-action" key={program.id} >{program.language}</a > </template> </ul> </lightning-card> </template>
templateLoopingForEach.css
.list-group { display: -ms-flexbox; display: flex; -ms-flex-direction: column; flex-direction: column; padding-left: 0; margin-bottom: 0; width: 50%; } .list-group-item:first-child { border-top-left-radius: 0.25rem; border-top-right-radius: 0.25rem; } .list-group-item-action { color: #495057; text-align: inherit; text-decoration: none; } .list-group-item { position: relative; display: block; padding: 0.75rem 1.25rem; margin-bottom: -1px; background-color: #fff; border: 1px solid rgba(0, 0, 0, 0.125); } .list-group-item:last-child { margin-bottom: 0; border-bottom-right-radius: 0.25rem; border-bottom-left-radius: 0.25rem; }
templateLoopingForEach.js-meta.xml
<?xml version="1.0" encoding="UTF-8"?> <LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata" fqn="templateLoopingForEach"> <apiVersion>46.0</apiVersion> <isExposed>true</isExposed> <targets> <target>lightning__AppPage</target> <target>lightning__RecordPage</target> <target>lightning__HomePage</target> </targets> </LightningComponentBundle>
templateLoopingForEach.js-meta.xml
templateLoopingForEach.js-meta.xml
is a configuration file- The configuration file defines the metadata values for the component, including the design configuration for Lightning App Builder and Experience Builder.
- This file only show your component in app builder
for:each with Array demo explanation
- Inside the
templateLoopingForEach.html
the firstlightning-card
is for normal array demo for:each
is taking an ArraycarList
which is a private property inside thetemplateLoopingForEach.js
- we have used
car
alias for the current item of an array and mapped it tofor:item
- As
key
should be unique and in this case, our all cars name is unique, so we have used their name as a key
for:each with an array of objects demo explanation
- Inside the
templateLoopingForEach.html
the secondlightning-card
is for array of objects demo for:each
is taking an ArrayprogrammingList
which is a private property inside thetemplateLoopingForEach.js
- we have used
program
alias for the current item of an array and mapped it tofor:item
- To access any property of an object, we have to use dot notation. for example
program.language
- As key should be unique and in this case, we have a unique id for each object, so we are using
program.id
templateLoopingForEach.css
you can update based on your styling
iterator in LWC(Lightning Web Component)
To apply special behavior to the first or last item in a list, use the iterator directive, iterator:iteratorName={array}. Use the iterator directive on a template tag.
Use iteratorName to access these properties:
- value—The value of the item in the list. Use this property to access the properties of the array. For example, iteratorName.value.propertyName.
- index—The index of the item in the list.
- first—A boolean value indicating whether this item is the first item in the list.
- last—A boolean value indicating whether this item is the last item in the list.
iterator LWC Example
accountListIteratorLWC.html
<lightning-card title="Account List using iterator" icon-name="custom:custom63">
<div class="slds-m-around_medium">
<template iterator:it={accounts.data}>
<p key={it.value.Id}>
{it.value.Name}
</p>
</template>
<template if:true={accounts.error}>
{accounts.error}
</template>
</div>
</lightning-card>
</template>
accountListIteratorLWC.js
import
{ LightningElement, wire } from 'lwc';
import
getAccountList from '@salesforce/apex/AccountHelper.getAccountList';
export default
class
AccountListForEachLWC extends
LightningElement {
@wire(getAccountList) accounts;
}
accountListIteratorLWC.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>
- Efficient Rendering: The
- Use HTML Template
- Element Rendering
- UI Elements, Value Providers, Expressions, aura:find, aura:if and aura:iteration
- Private – Non Reactive Properties
- Private – Reactive Properties
- Public Properties
- Public Boolean Properties
- Public Methods
- Getter Properties
- connectedCallback
- constructor
- connectedCallback and disconnectedCallback
- errorCallback
- render
- renderedCallback
- Lifecycle Flow
- renderCallback
- Compose child components
- Named Slots
- Unnamed Slots
- Shadow DOM
- Dispatching and Handling Events
- Communication b/w indepdent components
- Reusable JS Code
- Create & Dispatch Event
- Parent to Child Communication
- Child to Parent Communication
- Handle Event
- Compositions
- Events
- Use of Wire Service
- Example
- Error Handling
- Understanding LDS Concept
- LDS – View Record
- LDS – Create Record
- LDS – Edit Record
- LDS – Delete Record
- LDS – RecordViewForm and RecordEditForm
- LDS – RecordForm
- Calling Apex Method with Wire Decorator
- Imperative Method call to read the data
- Apex method call with the parameters
- Import Apex Methods
- Expose Apex Methods to Components
- Wire Apex Methods
- Imperative Apex
- Toast Message Notification
- Record Id and Object from the current page
- Navigation Service
- Meta File Configuration
- Usage in Lightning Page
- Using LWC in Aura Component
- Using LWC in Visualforce Page
- Lightning App builder
- Flow
- Quick Action
- Referring Custom Labels
- Referrring Static Resources
0 Comments