简体   繁体   English

Angular 2 ng-class取决于功能

[英]Angular 2 ng-class depending on function

Im trying to change the class of some elements based on an array. 我试图基于数组更改某些元素的类。 I have declared a function to return a boolean and say if the string(state/class) is contained in the array. 我已经声明了一个返回布尔值的函数,并说该字符串(状态/类)是否包含在数组中。 I have call it isState(st: string) {return (this.ArrayWithClasses.indexOf(st) > 0)} 我称它为isState(st: string) {return (this.ArrayWithClasses.indexOf(st) > 0)}

And then I do 然后我做

[ngClass]="{'class-I-Want-To-Activate': isState('evaluating-this-state') }"

But it is´t working. 但这是行不通的。 You see my mistake? 你看到我的错了吗? A best solution? 最佳解决方案?

Edit: It is working if I use just a boolean to toggle the class. 编辑:如果我仅使用布尔值来切换课程,那是可行的。 So I consider if function is what is wrong... 所以我考虑功能是否有问题...

Use the below 使用以下

isState(st: string) {
    let temp=this.ArrayWithClasses.indexOf(st)
    if(temp)
        return true;
    else
        return false;
}

You shouldn't check if indexOf() value is > 0 , because, if that string is located on the first place in array, you will get 0. 您不应该检查indexOf()值是否> 0 ,因为如果该字符串位于数组的第一位,您将得到0。

isState(st: string) {
    let temp = this.ArrayWithClasses.indexOf(st);
    if(temp != -1)
        return true;
    else
        return false;
}

If searched string is not located in the array , you will get -1 value for that. 如果搜索到的字符串不在数组中,则将获得-1值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM