Overview
ThehelloConditionalRendering component demonstrates conditional rendering in Lightning Web Components. It shows how to use the lwc:if and lwc:else directives to conditionally display different content based on component state.
What It Does
This component displays different messages based on whether a checkbox is checked. When the “Show details” checkbox is selected, it shows “These are the details!” Otherwise, it displays “Not showing details.” This demonstrates how to conditionally render elements in the template.Component Code
Key Concepts
- lwc:if Directive: Renders content when the expression evaluates to true
- lwc:else Directive: Renders alternative content when the lwc:if condition is false
- Boolean Properties: The
areDetailsVisibleproperty tracks the checkbox state - Checkbox Events: The
event.target.checkedprovides the checkbox’s boolean value - Conditional DOM: Elements are added/removed from the DOM based on the condition
How It Works
- The checkbox is initially unchecked, so
areDetailsVisibleisfalse - The
lwc:elseblock renders “Not showing details” - When the user checks the checkbox,
handleChangesetsareDetailsVisibletotrue - The
lwc:ifblock renders “These are the details!” - The
lwc:elseblock is removed from the DOM
Important Notes
- The
lwc:ifandlwc:elsedirectives must be used on<template>tags - The
lwc:elsemust immediately follow thelwc:ifblock - Content is completely added or removed from the DOM, not just hidden with CSS
- For three-way conditions, you can use
lwc:elseif
Usage Example
To use this component in your Salesforce org:- Initially displays: “Not showing details”
- Check the “Show details” checkbox
- Displays: “These are the details!”
- Uncheck the checkbox
- Returns to: “Not showing details”
