Home Salesforce Reusable Compare Element in Lightning Web Component

Reusable Compare Element in Lightning Web Component

by Dhanik Lal Sahni

Most of time we need to compare values or two controls in record pages. Instead of writing code at multiple places we can create compare element in lightning web component and we can use this at required pages single or multiple times.

Compare Element Requirement

  1. That element’s value should compare with other element
  2. That should compare values in same element

To compare with element, we need to find that element. By default we can not access other component’s element.  To access element of other component or parent component we have to pass that component as property.

//Page
export default class AppForm extends LightningElement {
    parent=this;
}

//Template
<c-compare-element parent={parent} />

Getting other component’s Value

We can find other’s component’s element using data-id or class attribute.

//using css class name
this.parent.template.querySelector('classname');
//using data-id element
this.parent.template.querySelector("lightning-input[data-id=name]")

Complete Code:

Test Compare Element:

To test above custom element we have to use that in another web component.  Take this example, we are adding custom component to compare date type field with class name ‘name’.  It is saying that custom element value should be less then comparing element’s value.  For this we have to use operator element.  We are passing parent element or container element using parent attribute.

<c-compare-element name="dobCompare" class="compare" type="date" compare-to=".name" operator="<=" parent={parent} error-message="Confirm Patient DOB should be less then DOB" label="Confirm Patient DOB"></c-compare-element>

Take another example where we need to compare specific value when user is entering. We can use attribute value-to-compare to compare value.

<c-compare-element name="numCompare" value-to-compare="2020" class="comparetwo" type="number" operator="=" parent={parent} error-message="Value and compare value not matching. It should be 2020" label="Current Year"></c-compare-element>

Test Component Code:

Demo Screen

References:

https://developer.salesforce.com/docs/component-library/documentation/en/lwc

You may also like

Leave a Comment