Multiple classes in ngClass

I am trying to add some values ​​to * ngClass, which used to work on previous alpha versions and now does not seem to work on angular2 beta:

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

An error message is displayed:

EXCEPTION: TypeError: it is impossible to read the 'add' property from undefined in [['fa', 'fa-star'] in PostView @ 30: 27]

What am I missing here?

+5
source share
3 answers

You must use square brackets to create property bindings. See this panel

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

If you are not going to change these classes dynamically, then using ngClass is redundant. You can simply use class="fa fa-star" in your template.

ngClass should be used when you want to dynamically turn them on and off. There is an example in the docs:

Your component will have a method:

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

then use ngClass in your template like this:

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

You can also create a string containing several classes.

In this case, addClass is the @Input var variable containing the class name, and active is the boolean value that sets the active class

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

Source: https://habr.com/ru/post/1013099/


All Articles