html code

Toggle Class Dynamically in Lightning Web Components (LWC)

In this straightforward situation, the objective is to toggle the visibility of a div, but the conventional <template if:true> tag is not applicable. Consider a scenario where a loop is in use.

We will explore two alternative methods for achieving dynamic show/hide functionality in LWC without relying on the <template if:true> approach.

Simplified Method for Toggling Class

<template>
    <button class={cssClass} onclick={handleToggleClick}>
        <lightning-icon icon-name={iconName}></lightning-icon>
        Non Profit        
    </button>
</template>
import { LightningElement, track} from 'lwc';

export default class PcSelectButtonFramework extends LightningElement {
    buttonClicked; //defaulted to false

    @track cssClass = 'slds-button slds-button_neutral';
    @track iconName = '';
    // Handles click on the 'Show/hide content' button
    handleToggleClick() {
        this.buttonClicked = !this.buttonClicked; //set to true if false, false if true.
        this.cssClass = this.buttonClicked ? 'slds-button slds-button_outline-brand' : 'slds-button slds-button_neutral';
        this.iconName = this.buttonClicked ? 'utility:check' : '';
    }

Toggle using the classList Method

/*to show the image*/
.SelectedBorderOrgType .markIcon {
  display: block;
}
/*to hide the image*/
.NonSelectedBorderOrgType .markIcon {
  display: none;
}
.SelectedBorderOrgType .pillLabel1 {
  font-weight: 600;
}
.NonSelectedBorderOrgType{
  font-weight : normal;
}
<div class="NonSelectedBorderOrgType" onclick={toggleOrgType}>
    <img class="markIcon" src={markIcon} alt='marked'>
    <div class="pillLabel1">{type.LKUP_DSC__c}</div>
</div>
toggleOrgType(event){
const evt = event.currentTarget;
evt.classList.toggle('SelectedBorderOrgType');
evt.classList.toggle('NonSelectedBorderOrgType');
}