In my Angular component I have the following code:
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-myApp',
templateUrl: './my-app.component.html',
styleUrls: ['./my-app.component.scss']
})
export class MyApp implements OnInit {
accordion1: boolean;
accordion2: boolean;
accordion3: boolean;
accordionAll: boolean;
constructor() { }
ngOnInit() {
}
toggleAll(): void {
this.accordionAll1 = !this.accordionAll
this.accordion1 = this.accordionAll;
this.accordion2 = this.accordionAll;
this.accordion3 = this.accordionAll;
}
}
So with this I can have individual buttons that can toggle the state to true or false with e.g.:
<div (click)="accordion1 = !accordion1" [ngClass]="accordion1 ? 'is-active' : ''"></div>
or I can make all of them true or false at the same time if I click on the button that has:
<div (click)="toggleAll()" [ngClass]="accordionAll ? 'is-active' : ''"></div>
And this works as intended. However, if the starting state of accordionAll
is false, and all the other states are individually clicked to a true state, accordionAll
will stay false. But what I would like is for it to turn true if all of the others are individually either true or false.
CodePudding user response:
this.accordionAll
will only true if accordion1
, accordion2
, and accordion3
are true
And
this.accordionAll
will only false if accordion1
or accordion2
or accordion3
is false
In templete:
<div (click)="accordion1 = !accordion1; shouldToggleAll()" [ngClass]="accordion1 ? 'is-active' : ''"></div>
<div (click)="accordion2 = !accordion2; shouldToggleAll()" [ngClass]="accordion2 ? 'is-active' : ''"></div>
<div (click)="accordion3 = !accordion3; shouldToggleAll()" [ngClass]="accordion3 ? 'is-active' : ''"></div>
In ts file
shouldToggleAll() {
this.accordionAll = this.accordion1 && this.accordion2 && this.accordion3;
}