Home > Software design >  toggle ngbAccordion from typscript File
toggle ngbAccordion from typscript File

Time:07-25

I want toggle the accordion from my component.ts file with a Button, how should I do it?

My html Code:

<button (click)="toggleAcc()" type="button" >Primary</button>
    <ngb-accordion id="acc1" #acc="ngbAccordion" activeIds="ngb-panel-0">
                <ngb-panel id="detailAcc">
                    <ng-template ngbPanelTitle>
                        <span>&#9733; <b>Fancy</b> title &#9733;</span>
                    </ng-template>
                    <ng-template ngbPanelContent>
                       Hello World!!!!
                    </ng-template>
                </ngb-panel>
            </ngb-accordion>

I want some script for toggleAcc method

@Component({
  selector: 'my-component',
  templateUrl: './my-component.html'
})

toggleAcc(){
     **********Some Code Here that can collapse and expand accordion*********
}

I use Angular 14, bootstrap 5 and ng-bootstrap12

CodePudding user response:

Solution 1: Provide panel id and toggle.

import { Component, ViewChild } from '@angular/core';
import { NgbAccordion } from '@ng-bootstrap/ng-bootstrap';

@ViewChild('acc') acc: NgbAccordion;

toggleAcc() {
  this.acc.toggle('detailAcc');
}

Solution 2: Iterate panels array to get all panel id and toggle each.

import { Component, ViewChild } from '@angular/core';
import { NgbAccordion } from '@ng-bootstrap/ng-bootstrap';

@ViewChild('acc') acc: NgbAccordion;

toggleAcc() {
  for (let panelId of this.acc.panels.map((x) => x.id)) {
    this.acc.toggle(panelId);
  }
}

Sample StackBlitz Demo

  • Related