There are 2 special directive which is being used for conditional rendering of DOM element.
1. if:true
1. if:true
2. if:false
<template if:true={expression}>
Render when expression is true
</template>
<template if:false={expression}>
Render when expression is false
</template>
Notes -
1. Expression can be JavaScript property
2. Can be property of an object defined in JavaScript. example {employee.name}
3. Ternary operator can not be used inside expression.
4. Array also can not be used in the expression.
5. To use computed value use getters.
Here is component code which have if-true if-false also computed expression in if-directive.
<template>
<lightning-card title="Conditional Rendering">
<div class="slds-m-around_medium">
<lightning-button
variant="brand"
label="Show Data"
title="Show Data"
onclick={handleClick} class="slds-m-left_x-small">
</lightning-button>
<template if:true={isVisible}>
<div >This is If-true directive example</div>
</template>
<template if:false={isVisible}>
<div >This is If-false directive example,
Please click Button to see if-true content</div>
</template>
<lightning-input type="text" label="Enter Text" onkeyup={changeHandler}>
</lightning-input>
<template if:true={helloCheck}>
<div>Congratulations you typed correctly. {typedValue}
</div>
</template>
</div>
</lightning-card>
</template>
Java script code
import { LightningElement } from 'lwc';
export default class HelloConditionalRendering extends LightningElement {
isVisible = false;
typedValue;
handleClick(){
this.isVisible = true;
}
changeHandler(event){
this.typedValue = event.target.value;
}
get helloCheck(){
return this.typedValue === "Hello";
}
}
No comments:
Post a Comment