I am developing an Angular accordion feature that allows only one accordion to be open at a time. I want to implement the functionality where on a second click, the currently open accordion will close. Currently, I can only open one accordion at a time.
accordion-group.component.ts
import { Component, Input } from '@angular/core';
@Component({
selector: 'app-accordion-group',
templateUrl: './accordion-group.component.html',
styleUrls: ['./accordion-group.component.css']
})
export class AccordionGroupComponent {
items = ['accordion1', 'accordion2', 'accordion3'];
selectedIndex;
select(i){
this.selectedIndex = i;
}
}
accordion-group.component.html
<app-accordion
*ngFor="let item of items; let i = index"
(click)="select(i)"
[selectedIndex]="selectedIndex"
[index]="i"
[item]="item">
</app-accordion>
accordion.component.html
<div
class="accordion"
[ngClass]="currentClass">
</div>
accordion.component.ts
import { Component, Input, OnChanges } from "@angular/core";
@Component({
selector: "app-accordion",
templateUrl: "./accordion.component.html",
styleUrls: ["./accordion.component.css"]
})
export class AccordionComponent implements OnChanges {
@Input() item;
@Input() selectedIndex;
@Input() index;
currentClass;
isOpen = false;
ngOnChanges(){
this.handleExpansion()
}
handleExpansion() {
this.isOpen = true;
if (this.isOpen && this.selectedIndex === this.index) this.currentClass = "expand";
else this.currentClass = "collapse";
}
}