Reputation: 131
How to have multiple panels > multiple accordions / multiple panels > single accordion closed with a button click?
tried using "closeOthers" mentioned in the api but that does not work
Upvotes: 0
Views: 2583
Reputation: 2084
In your html file
<ngb-accordion #acc="ngbAccordion" (panelChange)="beforeChange($event)">
<ngb-panel title="Title 1" id="id1">
<ng-template ngbPanelContent>
Panel 1
</ng-template>
</ngb-panel>
<ngb-panel title="Title 2" id="id2">
<ng-template ngbPanelContent>
Panel 2
</ng-template>
</ngb-panel>
<ngb-panel title="Title 3" id="id3">
<ng-template ngbPanelContent>
Panel 3
</ng-template>
</ngb-panel>
</ngb-accordion>
<button (click)="closeAll(acc)">Close all</button>
In your ts file
panels = [
{ id: 'id1', state: true },
{ id: 'id2', state: true },
{ id: 'id3', state: true }
];
public beforeChange($event: NgbPanelChangeEvent) {
for (let panel of this.panels)
if (panel.id === $event.panelId)
panel.state = !panel.state;
}
closeAll(acc) {
for (let panel of this.panels)
if (!panel.state)
acc.toggle(panel.id);
}
You mantain an array of objects with the panels id and state. When you interact with one of the panels you use beforeChange()
to change the state of the panel.
When you click on the button Close all you toggle()
only the panels with the open state.
Upvotes: 1