Если у вас есть динамический список, который вы получите от какого-то API, а затем вы хотите отобразить его в аккордеоне, вы можете создать класс CSS (visible
скажем), чтобы применить display: block
Затем создайте свойство (currentIndex
) в своем классе компонентов.Всякий раз, когда вы щелкаете по разделу, просто установите currentIndex
на индекс раздела, по которому щелкнули.И на основе currentIndex
примените класс visible
CSS с помощью [ngClass]
Шаблон:
<h2>Accordion</h2>
<div *ngFor="let section of sections; let i = index;">
<button class="accordion" (click) = "expand(i)">{{section.name}}</button>
<div class="panel"
[ngClass]="{ 'visible' : currentIndex === i }">
<p>{{section.content}}</p>
</div>
</div>
Класс:
export class HomePage {
currentIndex = -1;
sections = [
{ name: 'Section 1', content: 'Content 1' },
{ name: 'Section 2', content: 'Content 2' },
{ name: 'Section 3', content: 'Content 3' },
...
];
expand(index) {
if(this.currentIndex === index) {
this.currentIndex = null;
return;
}
this.currentIndex = index;
}
}
CSS:
...
.visible {
display: block;
}
Вот StackBlitz для вашей ссылки.