Lightning Web Components – How to Hide an Element Instead of Removing from DOM

I want to be able to show/hide a child LWC in a parent based on a variable (let's say showOrHideMe).
But this showOrHideMe boolean is coming from child component itself.
Trying the below approach would completely remove the element from dom. But I just want to hide the element allowing it to still present in DOM.

<div if:true={showOrHideMe}>
    <c-child-component
       ...
       ...
     >
</div>

also tried another approach, I'm setting the showOrHideStyle to "{display:none}" if I want to hide.
However this didn't work. I could not know why it doesn't picking the style dyanmically

<div style={showOrHideStyle}>
    <c-child-component
       ...
       ...
     >
</div>

I know the LWC is quite limited.
But please let me know if there is a solution

Best Answer

Your last attempt would work, but you don't use curly brackets in a style attribute:

this.showOrHideStyle = 'display:none';

Or, you can use the built-in CSS:

<div class={showOrHideStyle}>

...

this.showOrHideStyle = 'slds-hide';
Related Topic