Multiple classes in ngClass

谁都会走 提交于 2019-12-12 07:48:59

问题


I'm trying to add multiple values in *ngClass, what used to work on previous alpha releases and doesn't seem to work now on angular2 beta:

<i *ngClass="['fa','fa-star']"></i>

It produces an error:

EXCEPTION: TypeError: Cannot read property 'add' of undefined in [['fa','fa-star'] in PostView@30:27]

What am I missing here?


回答1:


You should use square brackets to create property binding. See this plunk

<i [ngClass]="['fa','fa-star']"></i>



回答2:


If you aren't going to be changing these classes dynamically then using ngClass is overkill. You can simply use class="fa fa-star" in your template.

ngClass should be used when you when you want to switch these on and off dynamically. There's an example in the docs:

Your component would have a method:

setClasses() {
  return {
    saveable: this.canSave,      // true
    modified: !this.isUnchanged, // false
    special: this.isSpecial,     // true
  }
}

then use ngClass in your template like so:

<div [ngClass]="setClasses()">This div is saveable and special</div>



回答3:


You can also build a string containing several classes.

In this case additionalClass is an @Input var containing the classname and active is a boolean that sets the active class

<div [ngClass]="(additionalClass + ' ' + (active ? 'active' : ''))"></div>


来源:https://stackoverflow.com/questions/34518235/multiple-classes-in-ngclass

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!