Description
You can use the if-else statement to conditionally execute code blocks based on a given condition.
HTML
<template>
<lightning-card title="If-Else Example">
<div class="slds-m-around_medium">
<lightning-input label="Enter your age:" type="number" value={age} onchange={handleAgeChange}></lightning-input>
<p>{message}</p>
</div>
</lightning-card>
</template>
Java Script
In this example, we have a lightning-input component to allow the user to input their age, and a paragraph to display a message based on their age using an if-else statement in the JavaScript controller.
import { LightningElement, track } from 'lwc';
export default class IfElseExample extends LightningElement {
@track age;
@track message;
handleAgeChange(event) {
this.age = event.target.value;
if (this.age < 18) {
this.message = 'You are not yet an adult.';
} else {
this.message = 'You are an adult.';
}
}
}
In the controller, we define a handleAgeChange() method to update the age property when the input value changes. We then use an if-else statement to check if the age is less than 18. If it is, we set the message to 'You are not yet an adult.' Otherwise, we set the message to 'You are an adult.'
Video
Video does not exists.