Search code examples
angularng-class

ngClass with three different states


I have no idea if this is the dumbest way to do this, but you have to start at some point, and this seemed like one way to go.

Anyways, I have created a div box. This box appears when a button is clicked, i.e. this click adds a class to the box. When the box appears it has two buttons - both which does something to the box.

Each button has these two functions:

States: Array<boolean> = new Array;

toggleState(firstIndex: number, secondIndex: number): void {
    let totalIndex = this.getTotalIndex(firstIndex, secondIndex);

    this.States[totalIndex] = !this.States[totalIndex];
}

getState(firstIndex: number, secondIndex: number): boolean {
    let totalIndex = this.getTotalIndex (firstIndex, secondIndex);

    return this.States[totalIndex];
}

This is just a way for me to get the state for each individual item/ID, where this box can appear. But again, I then have two other buttons with similar functions (only the name differs).

The buttons are then activated by:

<a (click)="toggleState1(firstIndex, secondIndex)">Button 1</a>
<a (click)="toggleState2(firstIndex, secondIndex)">Button 2</a>
<a (click)="toggleState3(firstIndex, secondIndex)">Button 3</a>

Now, the trouble I am having (which I can't get to work, and it also looks terrible tbh) is with the div box HTML, which currently looks like:

<div [ngClass]="getState1(firstIndex, secondIndex) ? getState2(firstIndex, secondIndex) ? getState3(firstIndex, secondIndex) ?
    'box-regular appear transparent' :  // here the box has appeared, and is transparent
    'box-regular' :                     // here the box has not yet appeared
    'box-regular appear enlarge' :      // here the box has appeared, and enlarged
    'box-regular appear'" >             // here the box has appeared

Now, when I run this, I can't seem to get all the buttons working. It's only two out of three that actually works. There is always one, no matter how I arrange it, that doesn't work.

So basically, what am I doing wrong here ? :)


Solution

  • As you always used box-regular then you can push it to the class property right away.

    <div class="box-regular" [ngClass]="[ { 'appear transparent' : getState1(firstIndex, secondIndex)}, { 'appear enlarge': getState3(firstIndex, secondIndex)} ]
    

    The syntax for multiple values in ngclass is [ngClass]= [ {}, {}],

    where object {} contains class value and condition like this { 'classValue': condition },

    If you need more than one class then use ternary operator but int this way:

    [ngClass]=[ condition ? true : false, condition2 ? true: false, etc]