Lightning Web Component Reflect JavaScript Properties as a HTML Attributes

Let’s understand here how we can able to set the HTML properties from the lightning web component properties which are almost similar like how you are setting HTML attributes using the createAttribute() method. You can control whether public JavaScript properties appear as attributes in the rendered HTML of a Lightning web component. Allowing properties to appear as attributes are especially important when creating accessible components because screen readers and other assistive technologies use HTML attributes. All HTML attributes are reactive by default. When an attribute’s value changes in the component HTML, the component is re-rendered.When you take control of an attribute by exposing it as public property, the attribute no longer appears in the HTML output by default. To pass the value through to the rendered HTML as an attribute (to reflect the property), define a getter and setter for the property and call the setAttribute() method. You can also perform operations in the setter. Use a private property to hold the computed value. Decorate the private property with @track to make the property reactive. If the property’s value changes, the component rerenders.

 

In this example, we will be seeing how to set the title to a component on mouseover.

Create a lightning web component using the below SFDX command.

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

 

Use the below mycomponent.html code

<template>
    <h1> Component </h1>
</template>

 

Use the below mycomponent.js code. This javascript controller title as public property. It converts the title to uppercase and uses the tracked property privateTitle to hold the computed value of the title. The setter calls setAttribute() to reflect the property’s value to the HTML attribute

import { LightningElement,track,api } from 'lwc';

export default class Mycomponent extends LightningElement {
    @track privateTitle;
    @api
    get title() {
        return this.privateTitle;
    }
    set title(value) {
        this.privateTitle = value.toUpperCase();
      this.setAttribute('title', this.privateTitle);
    }
}

 

Use the below mycomponent.js-meta.xml code

<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata" fqn="helloWorld">
    <apiVersion>45.0</apiVersion>
    <isExposed>true</isExposed>
    <targets>
        <target>lightning__RecordPage</target>
    </targets>
</LightningComponentBundle>

 

 

Create a new lightning web component using this SFDX command. we will be calling the my-component from this parent component.

 

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

 

Use this parent1.html code

<template>
<c-mycomponent title="Hover Over the Component to See Me"></c-mycomponent>
</template>

 

Push the changes to scratch org and add the changes to page layout and you can able to see the title on mouseover as shown below.

 

 

 

To make sure that you understand how JavaScript properties reflect to HTML attributes, look at the same code without the call to setAttribute(). The generated HTML doesn’t include the title attribute. Now update the mycomponent.js as shown below.

 

update the mycomponent.js code  as shown below

 

import { LightningElement,track,api } from 'lwc';

export default class Mycomponent extends LightningElement {
    @track privateTitle;
    @api
    get title() {
        return this.privateTitle;
    }
    set title(value) {
        this.privateTitle = value.toUpperCase();
     // this.setAttribute('title', this.privateTitle);
    }
}

Push the changes to scratch org. Now when you mouseover on the parent component you dnt see the title appears. Similarly, you can use removeAttribute() to hide HTML attributes from the rendered HTML.

 

Lightning web Component updateRecord Example

Let us discuss here how to use lightning/uiRecordApi module adapters. This module includes wire adapters to record data and get default values to create records. It also includes JavaScript APIs to create, delete, update, and refresh records. one of the most of importance function is updateRecord that will be used to update the record in the database without using apex class.

Syntax 

the updateRecord syntax looks like below

import { updateRecord } from 'lightning/uiRecordApi';
updateRecord(recordInput: Record, clientOptions: Object): Promise<Record>
  • recordInput— (Required) A RecordInput object used to update the record. To create the object, call generateRecordInputForUpdate(record).
  • clientOptions— (Optional) To check for conflicts before you update a record, pass const clientOptions = {'ifUnmodifiedSince' : lastModifiedDate}. Get lastModifiedDate via a wire service adapter that returns a record object: const lastModifiedDate = record.fields.LastModifiedDate.value;.
  • A Promise object that resolves with the updated record. The record contains data for the fields in the record layout.

Create a Lightning Web component

create a new lightning web component using this SFDX command

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

use this updaterecord.html code

<template>
    <lightning-card title="Update  Account Record" icon-name="standard:record">
        <div class="slds-m-around_medium">
            <lightning-input label="Name" onchange={handleNameChange} class="slds-m-bottom_x-small"></lightning-input>
            <lightning-input label="Annual Revenue" type="number" onchange={handleNameChange} class="slds-m-bottom_x-small"></lightning-input>

            <lightning-input label="Phone" type="phone" onchange={handleNameChange} class="slds-m-bottom_x-small"></lightning-input>
            <lightning-input label="Fax" type="phone" onchange={handleNameChange} class="slds-m-bottom_x-small"></lightning-input>

            <lightning-button label="Update  Account" variant="brand" onclick={updateAccount}></lightning-button>
        </div>
    </lightning-card>
</template>

Use this updaterecord .js code

import {
LightningElement,
track,api,wire
} from 'lwc';
import {
ShowToastEvent
} from 'lightning/platformShowToastEvent';
import ACCOUNT_OBJECT from '@salesforce/schema/Account';
import NAME_FIELD from '@salesforce/schema/Account.Name';
import ID_FIELD from '@salesforce/schema/Account.ID';

import ANNUALREV_FIELD from '@salesforce/schema/Account.AnnualRevenue';
import Fax_FIELD from '@salesforce/schema/Account.Fax';
import PHONE_FIELD from '@salesforce/schema/Account.Phone';


import {
getRecord,
updateRecord,
generateRecordInputForUpdate,
getFieldValue,
} from 'lightning/uiRecordApi';
import {
CurrentPageReference
} from 'lightning/navigation';


export default class Updaterecord extends LightningElement {
@api recordId;
@track accountId;
@track name = 'Demo Account';
@track annualrev = 0;
@track fax = '1231234345345';
@track phone = '1231234345345';

handleNameChange(event) {
    this.accountId = undefined;
    console.log('label values --->>' + event.target.label);
    if (event.target.label === 'Name') {
        this.name = event.target.value;
    }
    if (event.target.label === 'Annual Revenue') {
        this.annualrev = event.target.value;
    }
    if (event.target.label === 'Fax') {
        this.fax = event.target.value;
    }
    if (event.target.label === 'Phone') {
        this.phone = event.target.value;
    }

}


updateAccount() {
    let record = {
        fields: {
            Id: this.recordId,
            Name: this.name,
            AnnualRevenue:this.annualrev ,
            Fax:this.fax ,
            Phone:this.phone,
        },
    };
    updateRecord(record)
        // eslint-disable-next-line no-unused-vars
        .then(() => {
            this.dispatchEvent(
                new ShowToastEvent({
                    title: 'Success',
                    message: 'Record Is Updated',
                    variant: 'sucess',
                }),
            );
        })
        .catch(error => {
            this.dispatchEvent(
                new ShowToastEvent({
                    title: 'Error on data save',
                    message: error.message.body,
                    variant: 'error',
                }),
            );
        });


}

}

use this updaterecord.js-meta.xml

<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata" fqn="helloWorld">
    <apiVersion>45.0</apiVersion>
    <isExposed>true</isExposed>
    <targets>
        <target>lightning__RecordPage</target>
    </targets>
</LightningComponentBundle>

 

Push changes to scratch org.

Push changes to scratch using this command and add this component to record page using lighting app builder

sfdx force:source:push

 

Understand  the code

The following JavaScript code will update the tracked properties when an input value is changed

handleNameChange(event) {
    this.accountId = undefined;
    console.log('label values --->>' + event.target.label);
    if (event.target.label === 'Name') {
        this.name = event.target.value;
    }
    if (event.target.label === 'Annual Revenue') {
        this.annualrev = event.target.value;
    }
    if (event.target.label === 'Fax') {
        this.fax = event.target.value;
    }
    if (event.target.label === 'Phone') {
        this.phone = event.target.value;
    }

}

The following code will call from the update button  which contains the record details for the update using the updateRecord function

updateAccount() {
    let record = {
        fields: {
            Id: this.recordId,
            Name: this.name,
            AnnualRevenue:this.annualrev ,
            Fax:this.fax ,
            Phone:this.phone,
        },
    };
    updateRecord(record)
        // eslint-disable-next-line no-unused-vars
        .then(() => {
            this.dispatchEvent(
                new ShowToastEvent({
                    title: 'Success',
                    message: 'Record Is Updated',
                    variant: 'sucess',
                }),
            );
        })
        .catch(error => {
            this.dispatchEvent(
                new ShowToastEvent({
                    title: 'Error on data save',
                    message: error.message.body,
                    variant: 'error',
                }),
            );
        });


}

 

 

 

Lightning web components Events

Let us discuss here how to use the lightning web component events to communicate between components. Lightning web components dispatch standard DOM events. Components can also create and dispatch custom events. Use events to communicate up the component containment hierarchy. Events in Lightning web components are built on DOM Events, a collection of APIs and objects available in every browser. we will be seeing here how to the events using the CustomEvent interface and publish-subscribe utility.

Create and Dispatch Events Using CustomEvent 

Let’s discuss here how to use to create events, using the CustomEvent interface. In Lightning web components, CustomEvent provides a more consistent experience across browsers, including Internet Explorer. It requires no setup or boilerplate, and it allows you to pass any kind of data via the detail property, which makes it flexible. Lightning web components implement the EventTarget interface, which allows them to dispatch events, listen for events, and handle events.
  1. To create an event, use the CustomEvent() constructor
    new CustomEvent('inptext', {
                detail: name
            });

     

  2. To dispatch an event, call the EventTarget.dispatchEvent()  method.
            this.dispatchEvent(selectEvent);
    

     

The CustomEvent constructor has one required parameter, which is a string indicating the event type. As a component author, you name the event type when you create the event. You can use any string as your event type. The below example shows how to use the CustomEvent constructor to fire the events and receive the events using the event object. In this example, we are firing the event from the eventsource component using the CustomEvent.Create a Lightning web component using the following SFDX command.

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

Use the below eventsource.html code . in this code we have an input text field that will fire an event on onchange of the input text.

<template>
    <lightning-card title="Event Source">
        <div class="slds-m-around_medium">
            <lightning-input name="textVal" label="Enter Text" onchange={handleChange}></lightning-input>
        </div>
    </lightning-card>
</template>

use the below eventsource.js code and in this code, we have an handleChange function that will fire the event using the CustomEvent.

import {
    LightningElement
} from 'lwc';


export default class Eventsource extends LightningElement {
    handleChange(event) {
        event.preventDefault();
        const name = event.target.value;
        const selectEvent = new CustomEvent('inptext', {
            detail: name
        });
        this.dispatchEvent(selectEvent);
    }
}

Use the below eventsource.js-meta.xml code

<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata" fqn="helloWorld">
    <apiVersion>45.0</apiVersion>
    <isExposed>true</isExposed>
    <targets>
        <target>lightning__RecordPage</target>
    </targets>
</LightningComponentBundle>

 

Now create an event container component that will receive the events form the eventsource. create lightning web components using the below SFDX command

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

Use the below eventcontainer.html code. To listen for events, use an HTML attribute with the syntax oneventtype Since our event type inptext, the listeners are oninptext  and call the handler function on oninptext events  as shown below

        <c-eventsource oninptext={handleSelect}></c-eventsource>

Use the below eventcontainer.html code

<template>
    <div class="slds-m-around_medium">
        You Enter {valueInp}
        <c-eventsource oninptext={handleSelect}></c-eventsource>
    </div>
</template>

Use the eventcontainer.js code.  Receiving components access the data in the detail property in the event listener’s handler function.

import {
    LightningElement,
    track
} from 'lwc';


export default class Eventcontainer extends LightningElement {
     @track valueInp;
     handleSelect(event) {

         const textVal = event.detail;
         this.valueInp = textVal;
         console.log('textVaal' + textVal);
     }
}

Use the below eventcontainer.js-meta.xml

<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata" fqn="helloWorld">
    <apiVersion>45.0</apiVersion>
    <isExposed>true</isExposed>
    <targets>
        <target>lightning__RecordPage</target>
    </targets>
</LightningComponentBundle>

The CustomEvent interface imposes no type requirements or structure on the detail property. However it’s important to send only primitive data. JavaScript passes all data types by reference except for primitives. If a component includes an object in its detail property, any listener can mutate that object without the component’s knowledge. This is a bad thing! It’s a best practice either to send only primitives, or to copy data to a new object before adding it to the detail property. Copying the data to a new object ensures that you’re sending only the data you want, and that the receiver can’t mutate your data.

Now if you see in the below image it shows the enter input data from the text box to container component. If you enter the text in the event source component, the CustomEvent will be fired and the same event details will be received at container component

 

 

Using publish-subscribe pattern

To communicate between components that aren’t in the same DOM tree, use a singleton library that follows the publish-subscribe pattern.In a publish-subscribe pattern, one component publishes an event. Other components subscribe to receive and handle the event. Every component that subscribes to the event receives the event. For example, if you add two components to a Lightning page in Lightning App Builder, use the pubsub module to send events between them. If you’re familiar with Aura, you may recognize that Aura application events follow the publish-subscribe pattern.

Please refer this link to get the publish-subscribe utility code.

Create a lightning web component using the below SFDX command.

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

in this publish source component, we have an input text filed from where we are firing the event on input onchange events.

<template>
    <lightning-card title="Source" >
        <div class="slds-m-around_medium">
            <lightning-input type="text" onchange={handleChange} class="slds-m-bottom_small" label="Enter Text"></lightning-input>
        </div>
    </lightning-card>
</template>

Use the below publishsource.js code which will be publishing the event using publish-subscribe utility

import {
    LightningElement,
    wire
} from 'lwc';
import {
    CurrentPageReference
} from 'lightning/navigation';
import {
    fireEvent
} from 'c/pubsub';
export default class Publishsource extends LightningElement {
    @wire(CurrentPageReference) pageRef;

    handleChange(event) {
        fireEvent(this.pageRef, 'inputChangeEvent', event.target.value);
    }
}

In the above JavaScript file, we have two imports that are required to fire the events

import {
    CurrentPageReference
} from 'lightning/navigation';
import {
    fireEvent
} from 'c/pubsub';

Wire the current page reference using wire adapter as shown below

    @wire(CurrentPageReference) pageRef;

Fire the event using this below code .here inputChangeEvent is the event name.

        fireEvent(this.pageRef, 'inputChangeEvent', event.target.value);

use the below publishsource.js-meta.xml code

<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata" fqn="helloWorld">
    <apiVersion>45.0</apiVersion>
    <isExposed>true</isExposed>
    <targets>
        <target>lightning__RecordPage</target>
    </targets>
</LightningComponentBundle>

create a publish receive that will listen the events .create a lightning web component using the below SFDX command.

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

Use the below publishreceiver.html code

<template>
    <lightning-card title="Target">

        {inpVal}
    </lightning-card>
</template>

Use the below publishreceiver.js code that will listen to the events using the life cycle callbacks

import {
    LightningElement,
    track,
    wire
} from 'lwc';
import {
    CurrentPageReference
} from 'lightning/navigation';
import {
    registerListener,
    unregisterAllListeners,
    fireEvent
} from 'c/pubsub';

export default class Publishreceiver extends LightningElement {
      @track inpVal;
      @wire(CurrentPageReference) pageRef;

      connectedCallback() {
          // subscribe to inputChangeEvent event
          registerListener('inputChangeEvent', this.handleChange, this);
      }

      disconnectedCallback() {
          // unsubscribe from inputChangeEvent event
          unregisterAllListeners(this);
      }

      handleChange(inpVal) {
          this.inpVal = inpVal;
      }
}

use the below publishreceiver.js-meta.xml code

<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata" fqn="helloWorld">
    <apiVersion>45.0</apiVersion>
    <isExposed>true</isExposed>
    <targets>
        <target>lightning__RecordPage</target>
    </targets>
</LightningComponentBundle>

 

Now you can able to see the event is firing from the source component which is handled by the target component as shown below.

 

 

Usage of for:each template directives in Lightning web components

Let’s discuss here how to use the lightning web component HTML template for:each directive to iterate through the collection of data. The power of Lightning Web Components is the templating system, which uses the virtual DOM to render components smartly and efficiently. As the name suggests, the attribute directives are altering the properties of an element to which they are attached and the structural ones are changing. Directives are special HTML attributes, like if:true and for:each, that gives you more power to manipulate the DOM in markup.HTML templates also render data to the DOM.  Please refer to this link for the development environment setup 

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. 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. When using the for:each directive, use for:item="currentItem" to access the current item.  To assign a key to the first element in the nested template, use the key={uniqueId} directive.

1: Create an Apex Class 

Create an apex class using the following SFDX command

sfdx force:apex:class:create -n AccountController -d force-app/main/default/apex

here below is the complete code and this class will get the list of accounts that will be displayed in UI.

public with sharing class AccountController {
    @AuraEnabled(cacheable=true)
    public static List<Account> getAccountList() {
        return [SELECT Id, Name  FROM Account];
    }
    @AuraEnabled(cacheable=true)
    public static List<Account> getInnerData() {
      return [SELECT Id, Name, (SELECT Id, Name FROM Contacts) FROM Account];
   }

}

 

2. Create Lightning web component

create a lightning web component using the following SFDX command.

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

In this component, we are using for each to render the list and the nested list also.

Use this foreach.html markup

<template>
    <lightning-card title="Simple Each Example" icon-name="custom:custom3">
        <div class="slds-m-around_medium">
            <template if:true={accounts.data}>
                <template for:each={accounts.data} for:item="acc">
                    <p key={acc.Id}>{acc.Name}</p>
                </template>
            </template>
        </div>
    </lightning-card>

    <lightning-card title="Inner Data Example" icon-name="custom:custom3">
        <div class="slds-m-around_medium">
            <template if:true={accountsInner.data}>
                <ul>
                    <template for:each={accountsInner.data} for:item="acc">
                        <li key={acc.Id}>{acc.Name}
                            <ul key={acc.Id}>
                                <template for:each={acc.Contacts} for:item="con">
                                    <li key={con.Id}>{con.Name}</li>
                                </template>
                            </ul>
                        </li>
                    </template>
                </ul>
            </template>
        </div>
    </lightning-card>
</template>

 

use the below foreach.js code

import {
        LightningElement,
        wire
} from 'lwc';
import getAccountList from '@salesforce/apex/AccountController.getAccountList';
import getInnerData from '@salesforce/apex/AccountController.getInnerData';

export default class Foreach extends LightningElement {
        @wire(getAccountList) accounts;
        @wire(getInnerData) accountsInner;
}

use the below foreach.css

li {
    list-style-type: circle;
}

li li {
    list-style-type: square;
}

 

use the below code for foreach.js-meta.xml

<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata" fqn="helloWorld">
    <apiVersion>45.0</apiVersion>
    <isExposed>true</isExposed>
    <targets>
        <target>lightning__RecordPage</target>
    </targets>
</LightningComponentBundle>

 

3. Push changes to scratch org.

Push changes to scratch using this command and add this component to record page using lighting app builder

sfdx force:source:push

After adding the lightning web component to record page using the app builder. you can able to see the data as shown below and one section contains the simple collection and another section contains the nested collections.

 

Understand the code 

The below code is used to iterate the array of data.  This example iterates over an array called accounts.data and assigning each element in the array to for:item value and assign a key to the first element in the nested template using the key={acc.Id} 

 

 <template for:each={accounts.data} for:item="acc">
                    <p key={acc.Id}>{acc.Name}</p>
                </template>

The below code is used to iterate the nested array of data. This example iterates over an array called accountsInner.data and assigning each element in the array to for:item value and assign a key to the first element in the nested template using the key={acc.Id} and in the inner template we are taking the reference from the outer template for:item and using the iteration using the for:each={acc.Contacts} .

 

<template if:true={accountsInner.data}>
                <ul>
                    <template for:each={accountsInner.data} for:item="acc">
                        <li key={acc.Id}>{acc.Name}
                            <ul key={acc.Id}>
                                <template for:each={acc.Contacts} for:item="con">
                                    <li key={con.Id}>{con.Name}</li>
                                </template>
                            </ul>
                        </li>
                    </template>
                </ul>
            </template>