Hi,
A directive is a special attribute that adds dynamic behavior to an HTML template. You can use certain directives on a root <template>
tag, a nested <template>
tag, or an HTML element such as a <p>
tag. Some directives are supported for use with different tags.
As part of this post we discuss the directives lwc:if | elseif={expression} and lwc:else
Before introducing lwc:if | elseif={expression} and lwc:else we had if:true
and if:false
The if:true
and if:false
directives are no longer recommended. They may be deprecated and removed in the future. Use lwc:if
, lwc:elseif
, and lwc:else
instead.
if:true|false={expression}
conditionally renders DOM elements in a template, calling the expression for each of if:true
and if:false
. In cases where you chain if:true
and if:false
directives, they are not as performant nor as lightweight as the lwc:if
, lwc:elseif
, and lwc:else
directives. See Render DOM Elements Conditionally.
The expression
can be a JavaScript identifier (for example, person
) or dot notation that accesses a property from an object (person.firstName
). The engine doesn’t allow computed expressions (person[2].name['John']
). To compute the value of expression
, use a getter in the JavaScript class.
lwc:if|elseif={expression} and lwc:else
Conditionally render DOM elements in a template. lwc:if
, lwc:elseif
, and lwc:else
supersede the if:true
and if:false
directives.
Use the conditional directives on nested <template>
tags, <div>
tags or other HTML elements, and on your custom components tags like <c-custom-cmp>
.
Both lwc:elseif
and lwc:else
must be immediately preceded by a sibling lwc:if
or lwc:elseif
.
Eg:1
<template lwc:if={expression}></template>
<template lwc:else></template>
Both lwc:if
and lwc:elseif
must evaluate an expression. However, lwc:else
must not have an attribute value.
Eg:2
<template lwc:if={expression}></template>
<template lwc:elseif={expression_elseif1}></template>
<template lwc:elseif={expression_elseif2}></template>
<template lwc:else></template>
The expression passed in to lwc:if
and lwc:elseif
supports simple dot notation. Complex expressions like !condition
, object?.property?.condition
or sum % 2 === 1
aren't supported. To compute such expressions, use a getter in the JavaScript class.
Note
lwc:if
, lwc:elseif
, and lwc:else
can't be applied to the same element and they cannot be combined with the if:true
and if:false
directives.
Reference:
No comments:
Post a Comment