I have a situation where there are a series of ngb-accordions created in an ngFor loop, one created for each item in the data that is labeled an accordion:
<span *ngFor="let item of menu.items">
<!-- accordion menus -->
<ngb-accordion
#pageAccordion="ngbAccordion"
*ngIf="item.url === '#accordion'" //in the json, says this item is an accordion
[activeIds]="activePanel"
[destroyOnHide]="false"
>
The component has a viewchild for this accordion:
@ViewChild('pageAccordion', { static: false })
pageAccordion: NgbAccordion;
And I want to collapse all accordions:
this.pageAccordion.collapseAll();
The problem is it only collapses the first one created in the ngFor loop. None of the other ones close.
How can I target or loop through all the dynamically created accordions and call their collapseAll
method?
I am using Angular 8 and Angular Bootstrap 5.0
You has severals ng-accordion, so use ViewChildren. (ViewChild only get the first ng-accordion)
@ViewChildren('pageAccordion') pageAccordions:QueryList<NgbAccordion>
//you can use also
//@ViewChildren(NgbAccordion) pageAccordions:QueryList<NgbAccordion>
//a function to close all the accordions
closeAll()
{
this.pageAccordions.forEach(acc => {
acc.collapseAll()
})
}