【问题标题】:ngClass with three different states具有三种不同状态的 ngClass
【发布时间】:2020-08-20 23:08:22
【问题描述】:

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

无论如何,我已经创建了一个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

现在,当我运行它时,我似乎无法让所有按钮都正常工作。真正有效的只有三分之二。总有一个,不管我怎么安排,都行不通。

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

【问题讨论】:

  • ngClass 中的语法不正确,您使用的是条件吗? true : false,你使用更多的条件而不是 true 和 false,它是不可读的。

标签: angular ng-class


【解决方案1】:

由于您一直使用 box-regular,因此您可以立即将其推送到类属性。

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

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

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

如果您需要多个类,则使用三元运算符,但 int 这种方式:

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

【讨论】:

  • 啊,你至少让我走上了正轨。根据angularjswiki.com/angular/…,建议的方法是:&lt;div [ngClass]="{'message': info.priority &lt; 10, 'warn': info.priority &gt; 10 &amp;&amp; info.priority &lt; 20, 'error fa fa-exclamation-triangle': info.priority&gt;30}"&gt;
  • 非常好。
【解决方案2】:

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

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

【讨论】:

    猜你喜欢
    • 2018-11-14
    • 1970-01-01
    • 2015-04-22
    • 1970-01-01
    • 1970-01-01
    • 2013-05-16
    • 2016-03-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多