I would expect something like this to work:
<button (click)="myAccordionGroup.expandAll()">Expand all</button>
<ion-accordion-group #myAccordionGroup>
<ion-accordion>
<ion-item slot="header">
<ion-label>First Accordion</ion-label>
</ion-item>
<div slot="content">First accordion content</div>
</ion-accordion>
<ion-accordion>
<ion-item slot="header">
<ion-label>Second Accordion</ion-label>
</ion-item>
<div slot="content">Second accordion content</div>
</ion-accordion>
</ion-accordion-group>
But IonAccordionGroup.expandAll
does not exist as a method. In fact, IonAccordionGroup
does not expose any methods at the time of this writing.
As a workaround, I managed to do it by manually assigning values to each ion-accordion
and then set the value of the ion-accordion-group
to an array containing all of those values. To collapse all accordions at once, I set the value of ion-accordion-group
to an empty array.
But I’m looking for a way that:
- does not force me to manually assign values to each of the
ion-accordion
elements. - does not force me to manage the
ion-accordion-group
state in my component.
At the time of this writing, IonAccordionGroup
does not provide a method that lets you do it in the way that you described.
Your “workaround” is the correct way to do it.
You can create a custom Angular directive to reduce complexity:
import { ContentChildren, Directive, QueryList } from "@angular/core";
import { IonAccordion, IonAccordionGroup } from "@ionic/angular/standalone";
@Directive({
selector: "[appAccordionGroupToggle]",
exportAs: "appAccordionGroupToggle",
standalone: true,
})
export class AccordionGroupToggleDirective {
// get a reference to the ion-accordion instances inside
@ContentChildren(IonAccordion) accordions!: QueryList<IonAccordion>;
// get a reference to the ion-accordion-group instance
constructor(private host: IonAccordionGroup) {}
expand() {
// setting the value of the ion-accordion-group to an array of all the
// ion-accordion values will expand all ion-accordions
this.host.value = this.accordions.map((accordion) => accordion.value);
}
collapse() {
// setting the value of the ion-accordion-group to an empty array will
// collapse all ion-accordions inside
this.host.value = [];
}
}
In your component, you can use it like this:
@Component({
...
standalone: true,
imports: [
...
AccordionGroupToggleDirective,
],
})
export class MyComponent {
}
<button (click)="toggler.expand()">Expand all</button>
<button (click)="toggler.collapse()">Collapse all</button>
<ion-accordion-group appAccordionGroupToggle
#toggler="appAccordionGroupToggle">
<ion-accordion>
<ion-item slot="header">
<ion-label>First Accordion</ion-label>
</ion-item>
<div slot="content">First accordion content</div>
</ion-accordion>
<ion-accordion>
<ion-item slot="header">
<ion-label>Second Accordion</ion-label>
</ion-item>
<div slot="content">Second accordion content</div>
</ion-accordion>
</ion-accordion-group>