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

No comments:

Post a Comment