Add Dropdown (Picklist) in Lightning Web Component.

In Aura Components we can use lightning-select to create dropdown. In Lightning Web Component there is a lightning-combobox component that allows to do this.

Here is example on how to do this in LWC:

LightningDropDown.html

LightningDropDown.js

import { LightningElement, track } from 'lwc';

export default class LightningDropDown extends LightningElement {
@track selectedColor = 'white';

get colorOptions() {
    return [
             { label: 'White', value: 'white' },     
             { label: 'Red', value: 'red' },
             { label: 'Green', value: 'green' },
             { label: 'Blue', value: 'blue' },
           ];
}

handleChange(event) {
        this.selectedColor = event.detail.value;
     }
}

How to show toast notification in Lightning Web Component example.

Let’s talk about toast notification pop ups in Salesforce Lightning. Toast notification can pop up and display error, warning, success or information messages. The style of the notification depends on the variant of the toast. You don’t have to set variant of the toast – default value is info. To use toast in Lightning Web Component you need to import ShowToastEvent from the lightning/platformShowToastEvent module.

import { ShowToastEvent } from 'lightning/platformShowToastEvent'

Javascript Controller:

import { LightningElement } from 'lwc';
import { ShowToastEvent } from 'lightning/platformShowToastEvent'

export default class ShowToastDemo extends LightningElement {
    showInfoToast() {
        this.showToast( 'Info Title', 'Info Message', 'info' );
    }
    showSuccessToast() {
        this.showToast( 'Success Title', 'Success Message', 'success' );
    }
    showWarningToast() {
        this.showToast( 'Warning Title', 'Warning Message', 'warning' );
    }
    showErrorToast() {
        this.showToast( 'Error Title', 'Error Message', 'error' );
    }

    showToast( title, message, variantStr ) {
        const event = new ShowToastEvent({
            title: title,
            message: message,
            variant: variantStr
        });
        this.dispatchEvent(event);
    }
}

In our demo lightning web component we will add 4 buttons – one for each variant of toast notification:

Info Toast Notification:

Success Toast Notification:

Warning Toast Notification:

Error Toast Notification:

Basic differences between Aura Component and Lightning Web Components in HTML

Lightning Web Components is an implementation of the W3C’s Web Components standards.The Aura Component framework is a UI framework for developing web apps for mobile and desktop devices. It’s a modern framework for building single-page applications with dynamic, responsive user interfaces for Lightning Platform apps. It uses JavaScript on the client side and Apex on the server side.

Aura components can contain Lightning web components but Lightning web components can’t contain Aura components.

When you create an Aura component , it has the following files:
example.cmp, exampleController.js, exampleHelper.js, exampleRenderer.js, example.css and a configuration file.
When you create a Lightning web component, it has the following files:
example.html, example.js, example.css and a configuration file

Here are the basic differences in HTMl between Aura and LWC:

  • An Aura component contains markup in a .cmp file. The file starts with an <aura:component> tag and can contain HTML and Aura-specific tags.A Lightning web component contains markup in a .html file.
  • The file starts with a <template> tag and can contain HTML and directives for dynamic content.
  • In Aura component the attributes are defined in <aura:attribute> tag. While in Lightning web component it is defined as JS properties.
  • Syntax for Dynamic component in Aura is {!v.count}, while in Lightning web component it is {count}. You don’t need the ‘!’ and the ‘v.’ .
  • Conditional markup changes from :
    <aura:if isTrue=”{!v.showsection}”>
        to
    <template if:true={showsection}></template>
    ( Please notice that there is no quotes around the dynamic content. This is true through out the LWC. )
  • In Aura you can do additional conditions in your expression language. In LWC, you will have to move this condition to JS. For example in Aura to check for a condition if the count is 1 , you can add it in the <aura:if> for example:
              <aura:if isTrue=”{!v.count > 1}”>
                          //show content
             </aura:if>

    While in lwc we have to move this logic to JS and use the variable in the expression language:
    HTML will look like this in LWC :

                 <template if:true={hasMoreThanOne}>
                           //show content
                 </template>

    JS will look like this:
                import { LightningElement, api } from ‘lwc’;
                export default class Paginator extends LightningElement {
                        @api count;
                         get hasMoreThanOne() {
                               return this.count === 1;
                         }
                 }

  • In Aura for Iterations we use <aura:iteration>, then use the ‘items’ attribute to pass the collection and ‘var’ attribute to pick the individual item from the collections. In LWC we can use ‘for:each’ and ‘for:item’ for passing collections and individual variable accordingly.
    Aura:
             <aura:iteration items=”{!v.properties}” var=”property”>
                    // show the data associated with each property
             </aura:iteration>
    LWC:
            <template for:each={properties.data.records}  for:item=”property”>
                   //show content
             </template>
  • We use the init handler in Aura to run code that we need to run before rendering an Aura component. In LWC we replace this with connectedCallback() lifecycle hook. There are multiple lifecycle hooks that you can use to run code at different stages of the component’s lifecycle.
  •  Self closing tags are not allowed in LWC, while they are allowed in Aura.
  • Aura CSS can be converted LWC CSS by removing ‘.THIS’
    To convert the Base Lightning components from Aura to LWC syntax, we can follow these points:
              * Change the colon that separates the namespace (lightning) and  component name (formattedNumber) to a dash.
              * Change the camel-case component name (formattedNumber) to a dash-separated name (formatted-number).
              * Change the camel-case attribute name (currencyCode) to a dash-separated name (currency-code).
    This will convert a lightning base component in Aura
         <lightning:formattedNumber/>
                             to
        <lightning-formatted-number></<lightning-formatted-number>

Lightning Web Component in Utility Bar example

Here I will show how to make lightning web component available to be used as Utility Bar Item.

First create new Lightning Web Component.

sfdx force:lightning:component:create --type lwc --componentname UtilityBarExample --outputdir force-app\main\default\lwc

Open meta configuration XML file utilityBarExample.js-meta.xml and change it – add targets lightning__UtilityBar and lightning__AppPage and change
isExposed to true, so the file looks like this:

Create Scratch org if you don’t have one (quick command that uses default config and 30 duration day for Scratch org):

sfdx force:org:create -f config\project-scratch-def.json --setalias LightningWebComponents --durationdays 30 --setdefaultusername --json --loglevel fatal

Push code to your scratch org:

sfdx force:source:push --json --loglevel fatal

Go to Setup –> Apps –> App Manager.

Select the app that you want to add Utility Item to and select Edit. Then go to Utility Items and add Utility Item.


You should be able to see your custom component in the list of available components.Now you can add this Lightning Web Component in Utility Bar.

Lightning Web Component Datatable example with sorting and search functionality.

Many people are familiar with lightning datatable component and how to use it in Aura Component. In this article I want to show example how to use lightning component in Lightning Web Component and build simple search by name and column sorting.

First we need to create an apex class.

You can create it either in Salesforce UI or Developer Console or do it in Visual Studio Code with SFDX command:

sfdx force:apex:class:create --classname GetAccounts --template DefaultApexClass --outputdir force-app\main\default\classes

Code for Apex class:

Second we will need to create Lightning Web Component budle.

sfdx force:lightning:component:create --type lwc -n LightningDatatableExample -d force-app/main/default/lwc

Code for html component:

JS controller:

To make sure component is visible in Lightning App Builder you need to add targets and change isExposed to true in LightningDatatableExample.js-meta.xml file:

How to create Popup Using Lightning Web Components?

Lightning Web Components is the new programming model that you can use to build Lightning components in Salesforce. Here Is how you can create a Popup in Salesforce using LWC.

The following is the JavaScript that foes in the filename.js

import { LightningElement , track } from 'lwc';

export default class PopUpExample extends LightningElement {
    @track openModal;
    openPopUp() {
        this.openModal = true;
    }
    closePopUp() {
        this.openModal = false;
    }
    saveAction(){
        // eslint-disable-next-line no-console
        console.log( 'saveaction is called');
        this.closePopUp();
    }
}

Here is the xml file

When you create a new lwc, make sure the isExposed is updated to True in the xml file. The default is false, the component will not show up in the Lightning Builder even if you deploy the component to your org. Also update the <targets> based on what your requirements are.

That’s it.. Hope it helps.

How to use static resource to style Lightning Web Components?

Here is a sample code on how to import and use static resources for styling your lwc.

I zipped my CSS file into folder and uploaded this into a static resource called ‘myResource’. Here is the JS code you would need to import this static Resource into your component.

import { LightningElement, track } from 'lwc';
import { loadStyle } from 'lightning/platformResourceLoader';
import myResource from '@salesforce/resourceUrl/myResource';
export default class CssExample extends LightningElement {
    @track textVal;
    changeHandler(event) {
        this.textVal = event.target.value;
    }
    renderedCallback() {
        Promise.all([
            loadStyle(this, myResource + '/styleSheet.css')
        ]).catch(error => {
             // eslint-disable-next-line no-console
             console.log(error);
            
        });
    }
}

Here is how you can use a style class that you have defined inside the static resource:

That’s it. Hope it helps 🙂