Saturday 28 October 2023

HTML Template Directives (lwc:if|elseif={expression} and lwc:else)

 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:iflwc: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:iflwc: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:iflwc: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 !conditionobject?.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:

https://developer.salesforce.com/docs/platform/lwc/guide/reference-directives.html?q=html+directives#directives-for-html-elements

No comments:

Post a Comment

How to include a screen flow in a Lightning Web Component

 Hi, Assume  you have a flow called "Quick Contact Creation" and API Name for the same is "Quick_Contact_Creation". To i...