0

Hello,

I develop a LWC and I have 2 displays because a condition.

They are very similar but a "div" element is inside the second display but it is on the top of the LWC.

This is my first display (it is only an example):

<lightning-layout-item>
<template for:each={data} for:item='aData'>
   {aData.label}     
</template>

My second display is something like this (it is only an example):

<lightning-layout-item>
<template if:false={isFullVersion}>
    <div>
</template>
<template for:each={data} for:item='aData'>
   {aData.label}     
</template>
<template if:false={isFullVersion}>
    </div>
</template>

The difference is the adding of the "div" element between the "" and the "" elements but the second display doesn't work (I can't deploy my LWC) because I can't only add a "div" (the opening "" only) element into a "template" element, I should add the opening and the closing (" and "").

My problem is I don't want to have 2 big conditions in my LWC like this (because it is not beautifull and it duplicates the code):

<lightning-layout-item>

<template if:true={isFullVersion}>
    <template for:each={data} for:item='aData'>
       {aData.label}
    </template>
</template>

<template if:false={isFullVersion}>
    <div>
        <template for:each={data} for:item='aData'>
           {aData.label}
        </template>
    </div>
</template>

Do you know if there is a way to do it properly (not duplicate my code)?

Thanks

5
  • so you want to wrap {aData.label} in div if isFullVersion is false other wise not right? Aug 3, 2022 at 16:19
  • I would like to wrap the foreach in a div element only when isFullVersion is false
    – Oupat
    Aug 3, 2022 at 16:20
  • so what is the purpose of having div? just for display? Aug 3, 2022 at 16:24
  • Yes, the div is for the display because it uses css
    – Oupat
    Aug 3, 2022 at 16:31
  • then you can apply the CSS dynamically using the class attribute. Aug 3, 2022 at 16:35

1 Answer 1

1

Looks like you want to change the styles based on the isFullVersion attribute value. So you need to add the CSS dynamically using the class attribute.

.css

.fullVersionStyle{
    display:block;
    // add more css 
}

.regularVersionStyle{
    display: inline;
    // add more CSS 
}

Write getter for a class attribute in JS controller.

.js

get divVersionClasses(){
    return this.isFullVersion ? 'fullVersionStyle' : 'regularVersionStyle';
}

Use the class in the HTML file.

.html

<template if:false={isFullVersion}>
    <div class={divVersionClasses}>
        <template for:each={data} for:item='aData'>
           {aData.label}
        </template>
    </div>
</template>
1
  • 1
    It is what I wanted, thank you.
    – Oupat
    Aug 4, 2022 at 6:44

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .