How to collapse and expand LWC accordion when an only a single accordion section is available
love your work
Problem- We need to have one account accordion which can be expanded and collapsed by the user but by default its launched as collapsed.
Solution:-
Link for the working code
- Played with properties of current LWC accordion and designed a custom solution
- The tricky part was to use “
allow-multiple-sections-open
” and set the currently active section “active-section-name"
as blank - Working code is as below .html file
<template> <lightning-accordion class="example-accordion" onsectiontoggle={handleToggleSection} active-section-name={accordianSection} allow-multiple-sections-open> <lightning-accordion-section name="A" label="Accordion Title A"> <lightning-button-menu slot="actions" alternative-text="Show menu" icon-size="x-small" menu-alignment="right"> <lightning-menu-item value="New" label="Menu Item One"></lightning-menu-item> <lightning-menu-item value="Edit" label="Menu Item Two"></lightning-menu-item> </lightning-button-menu> <p>This is the content area for section A.</p> <p>.</p> <p>.</p> <p>.</p> <p>The section height expands to fit your content.</p> </lightning-accordion-section> </lightning-accordion> </template>
.js file
import { LightningElement } from 'lwc'; export default class LightningExampleAccordionBasic extends LightningElement { accordianSection = ''; handleToggleSection(event) { if(this.accordianSection.length === 0){ this.accordianSection ='' } else{ this.accordianSection ='Account' } } }