I am trying to create an accordion, where you can click on each accordion, but I would also like to have another button where a click expands or collapses all accordions.
So right now I have this .ts
component:
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-faq',
templateUrl: './faq.component.html',
styleUrls: ['./faq.component.scss'],
})
export class FaqComponent implements OnInit {
accordion1: boolean;
accordion2: boolean;
accordion3: boolean;
accordionAll: boolean;
constructor() { }
ngOnInit() {
}
}
Now, each accordion is just some CSS, and then I can activate each one with:
<div class="accordion-header" (click)="accordion1 = !accordion1" [ngClass]="accordion1 ? 'is-active' : ''">Accordion 1</div>
And then I can give it some styling and activate some accordion content with that particular accordion1
state.
For the expand/collapse all I currently have something like this:
<div *ngIf="!accordionAll" (click)="accordion1 = true; accordion2 = true; accordion3 = true; accordionAll = true"></div>
<div *ngIf="accordionAll" (click)="accordion1 = false; accordion2 = false; accordion3 = false; accordionAll = false"></div>
Now, in some sense this works. But if I suddenly have 20 different accordions, this will be horrendeus. Also, I don't like that I need to have two divs, since some kind of animation (of e.g. an icon) doesn't work that well this way.
So my question is: How do I do this the "right" way, where it doesn't get a mess with many accordions, and where I can actually do the expand/collapse all with only one button ?
CodePudding user response:
Since you're traking the state of accordionAll
already, you don't need to pass a boolean to a method.
<div (click)="toggleAll()"></div>
toggleAll(): void {
this.accordionAll = !this.accordionAll
this.accordion1 = this.accordionAll;
this.accordion2 = this.accordionAll;
this.accordion3 = this.accordionAll
}
CodePudding user response:
I Think that something like this gonna work.
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-faq',
templateUrl: './faq.component.html',
styleUrls: ['./faq.component.scss'],
})
export class FaqComponent implements OnInit {
accordion1: boolean;
accordion2: boolean;
accordion3: boolean;
accordionAll: boolean;
constructor() { }
ngOnInit() {
}
toogleAll() {
this.accordion1 = this.accordionAll;
this.accordion2 = this.accordionAll;
this.accordion3 = this.accordionAll;
this.accordionAll = !this.accordionAll;
}
}
<div *ngIf="!accordionAll" (click)="toogleAll()"></div>
<div *ngIf="accordionAll" (click)="toogleAll()"></div>