Angular 4+ bootstrap NgbAccordion how to expand / collapse all

Ivonet picture Ivonet · Mar 23, 2018 · Viewed 21.5k times · Source

I've been playing around with angular in combination with ng-bootstrap and I am stumped about the following:

I have this NgbAccordion on my page:

<ngb-accordion #acc="ngbAccordion">
    <ngb-panel *ngFor="let container of answer.resultObj.containers.containers" title="{{container.metadata.title}}">
      <ng-template ngbPanelContent>
        <app-containers [container]="container"></app-containers>
      </ng-template>
    </ngb-panel>
  </ngb-accordion>

this results in a lit of ngb-panels all collapsed. This is precisely what I want and I can toggle the expansion of the app-container objects by clicking on them.

I also want a button to expand all the ngb-panels. I can't seem to get it to work. I found a nice example based on Angularjs (<2) but that does not work and the [isOpen] option that seemed to have been there at one time does not exist anymore?!

My angular component:

import {Component, Input} from '@angular/core';
import {Answer} from '../model/answer';
@Component({
  selector: 'app-answer',
  templateUrl: './answer.component.html',
  styleUrls: ['./answer.component.css'],
  providers: []
})
export class AnswerComponent {
  @Input() answer: Answer;

  constructor() {
  }
}

Any help would be appreciated...

Answer

David picture David · Mar 23, 2018

You can use the activeIds input on the accordion

https://ng-bootstrap.github.io/#/components/accordion/api

Basically, assign a unique id to each of your panels

<ngb-panel *ngFor="let container ...; let i= index" title="Panel{{i}}" id="panel-{{i}}"

and declare in your component a list of the active ids (= ids of the panels that must be open)

activeIds: string[] = [];

Then modify that list when you want to open/close the panels

this.activeIds = [];//All panels closed
this.activeIds = ['panel-1', 'panel-2']; //panels 1 and 2 are open

And bind this variable to the activeIds input of the accordion

<ngb-accordion #acc="ngbAccordion" [activeIds]="activeIds"

Finally, add the buttons

<button (click)="activeIds=[]" >close all</button>
<button (click)="openAll()" >open all</button>

openAll()
{
    this.activeIds = [/* add all panel ids here */];
}

I created a stackblitz to illustrate this

https://stackblitz.com/edit/angular-nzzwnc?file=app%2Fapp.component.ts