具有三种不同状态的ngClass

问题描述

我不知道这是否是最愚蠢的方式,但是您必须从某个时候开始,这似乎是一种方法

无论如何,我已经创建了一个div框。当单击按钮时,即出现此框,即此单击将一个添加到该框中。出现该框时,它有两个按钮-两者都对框起作用。

每个按钮具有以下两个功能

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];
}

这只是我获取每个单独的项目/ ID的状态的一种方式,可以在其中显示此框。但同样,我还有另外两个具有相似功能的按钮(只是名称不同)。

然后通过以下方式激活按钮:

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

现在,我遇到的麻烦(我无法上班,而且看上去也很糟糕)是div框HTML,当前看起来像这样:

<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

现在,当我运行此命令时,我似乎无法使所有按钮正常工作。实际有效的只有三分之二。总是有一个,无论我如何安排,都行不通。

所以基本上,我在这里做错了什么? :)

解决方法

由于您通常使用box-regular,所以可以立即将其推送到class属性。

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

ngclass中多个值的语法为[ngClass]= [ {},{}]

其中对象{}包含类值和条件,例如{'classValue':condition},

如果您需要多个类,请使用三元运算符,但以这种方式进行诠释:

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

如果我们将问题从“如何使用ngClass进行处理”改写为“如何在Angular中进行处理”,则答案将是-使用[class.your-class]="condition"语法。 文档特别强调了将其作为首选方法,甚至提到将来会弃用ngClass。

文档:https://angular.io/guide/attribute-binding#class-binding