Tag: Lightning web component

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.

 

Use the below mycomponent.html code

 

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

 

Use the below mycomponent.js-meta.xml code

 

 

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

 

 

Use this parent1.html code

 

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

 

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

  • 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

use this updaterecord.html code

Use this updaterecord .js code

use this updaterecord.js-meta.xml

 

Push changes to scratch org.

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

 

Understand  the code

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

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

 

 

 

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

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

     

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.

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.

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

Use the below eventsource.js-meta.xml code

 

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

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

Use the below eventcontainer.html code

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

Use the below eventcontainer.js-meta.xml

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.

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

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

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

Wire the current page reference using wire adapter as shown below

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

use the below publishsource.js-meta.xml code

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

Use the below publishreceiver.html code

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

use the below publishreceiver.js-meta.xml code

 

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

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

 

2. Create Lightning web component

create a lightning web component using the following SFDX command.

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

Use this foreach.html markup

 

use the below foreach.js code

use the below foreach.css

 

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

 

3. Push changes to scratch org.

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

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} 

 

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

 

 

 

 

 

 

 

Tracked Properties in Lightning web component

Let us understand how to use the Tracked Properties in Lightning web components. To track a private property’s value and re-render a component when it changes, decorate the property with @track.Tracked properties are also called private reactive properties. Modern JavaScript framework is supporting “reactive,” properties which mean it can automatically refresh your data when changes have happened to the property and what does mean “private reactive “.private reactive means the data changes are atomically refreshing on the UI and not exposed to the other components or an app builder.These properties are strictly inside the component. Now let us understand the ways you can take advantage of this in your apps. You can use a tracked property directly in a template. You can also use a tracked property indirectly in a getter of a property that’s used in a template. Refer this link for development environment setup

Create a Lightning web component using the SFDX command

Here is the simple component that will show the message on the UI using the JavaScript property

Here is the TrackedProperties.html code

Here is the TrackedProperties.js code

Here is the TrackedProperties.js-meta.xml

Push changes to scratch org and add the changes to record page .you can able to see as shown below.

Now when you click on update message the property is updated in JavaScript controller but the changes won’t update in the UI. You can able see the below message in chrome console when you click on “Update Message”

You can able to make the property trackable by using the track decorator .Import @track from the lwc module. This decorator is unique to the Lightning Web Components programming model.

You can use @track to decorate a property only; you can’t use it to decorate an object. You can decorate multiple properties with@track, but each property can have only one decorator. For example, you can’t decorate a property with both @track and @api. Let’s update the same code with the @track decorator which will reflect the changes to UI on button click.

update the JavaScript controller as shown below

Now when you click on the Update message you can able to see the result changes on the UI

Now let us make some more changes to make the @track property looks like a two-way data binding.

Update the TrackedProperties.html code as shown below

Update the JavaScript Controller as shown below

Now when you enter any text in input box the message will update like two-way binding as shown below

Now let’s look at sample code with a parent component passing property to a child component. This example will display the progress bar from the enter input number and we have two components here chartBar,apiProperty.

create a new lightning web component using the following SFDX command

Use this code in chartBar.html

Here is the chartBar.css

Now, let’s call this chartBar.html code from the parent component. now create a new lightning web component using the following SFDX syntax.

use this code in apiProperty.html

Use this code in the apiProperty.js class

 

Use this code in apiProperty.js-meta.xml

Push changes to scratch org and add apiProperty.html code to the record page .you can able to see the output as shown below

 

The c-api-property component uses its tracked percentage property to pass a value down to the public percentage property on its child c-chart-bar component. Components that consume c-api-property can’t get or set its percentage property because tracked properties are private.Its you want to make it as public property you need to use the @api decorator .

 

 

 

 

 

 

 

 

 

 

,