Saturday, 28 March 2020

Conditional rendering in Ligthing web component

To render a DOM element in a template only when certain conditions are met,we use conditional rendering.

1.Render element only when condition evaluates to true.

 syntax : <template if:true={propertyName}></template>

2.Render element only when condition evaluates to false.

 syntax : <template if:false={propertyName}></template>

Note :
1.LWC will not support conditional operators or expression
evolution methods in markup.
2.Directives are only allowed on a template element.

ex :
  <template>
    <lightning-card title="Conditional Rendering">
        <div class="slds-p-around_small">
        <lightning-input type="checkbox" label="Check" checked={flag} onchange={handleChange}>          </lightning-input>
            <br></br>
        <template if:false={flag}>
            <div class="slds-p-around_small">POSITIVE SCENARIO</div>
        </template>
        <template if:true={flag}>
            <div class="slds-p-around_small" >NEGATIVE SCENARIO</div>
        </template>
      </div>
    </lightning-card>
</template>

  import { LightningElement, track } from 'lwc';
  export default class ConditionalRendering extends LightningElement {
    @track flag = false;

    handleChange(event) {
        this.flag = event.target.checked;
    }
}

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";