Saturday, 28 March 2020

HTML5 Attributes in Lightning web components

HTML5 Attributes or data Attributes in LWC
================================

1.The data-* attributes is used to store custom data private to the page or application.
2.The data-* attributes gives us the ability to embed custom data attributes on all HTML elements.
3.The data-* attributes consists of two parts

a. The attribute name should not contain any uppercase letters,and must be at least one character long after the prefix "data-".
b. The attribute value can be any string.

Note : Custom attributes prefixed with "data-" will be completely ignored by the user agent.

ex 1 :

<button data-mylabel="html-demo" onclick={handleClick} class="slds-mleft_x-small"> CLICK </button>

import {LightningElement,track} from 'lwc';
export default class Attributes extends LightningElement{
   @track clickedLabel;
 
   handleClick(event){
     this.clickedLabel=event.target.dataset.mylabel;
   }
}

ex 2 :
<a onclick={handleClick} data-target-id="overview">Overview</a>

handleClick(event){
 let targetId=event.target.dataset.targetId;
}

ex 3 :
 we can use data- attributes to select an element.In LWC we use only querySelector or querySelectorAll for getting/selecting
 elements(s). 

 select the input and set the value.

<lightning-input data-my-id="myinput" class="second-class"></lightning-input>

this.template.querySelector("lightning-input[data-my-id=myinput]").value = "Some Value";

No comments:

Post a Comment