具有三种不同状态的 ngClass

ngClass with three different states

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

无论如何,我已经创建了一个 div 框。单击按钮时会出现此框,即此单击会向框添加 class。当框出现时,它有两个按钮 - 两个按钮都对框有所帮助。

每个按钮都有这两个功能:

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

这只是我获取每个人的状态的一种方式 item/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]= [ {}, {}],

其中对象 {} 包含 class 值和条件,如下所示 { 'classValue': 条件 },

如果您需要多个 class 则使用三元运算符,但 int 是这样的:

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

如果我们将问题从“如何使用 ngClass 做到这一点”重新表述为“如何在 Angular 中做到这一点”,答案将是 - 使用 [class.your-class]="condition" 语法。 文档特别强调这是一种首选方法,甚至提到 ngClass 将来会被弃用。

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