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?
Using multiple classes is the real reason to use the NgClass directive. You can think of NgClass as being able to specify multiple [class. class-name] on the same element.
You can use the ngClass directive to conditionally apply one-to-many classes or styles to an element, giving you an effective way to operate with multiple classes or styles at once.
ngClass is more powerful. It allows you to bind a string of classes, an array of strings, or an object like in your example. The above two lines of code is with respect to CSS class binding in Angular. There are basically 2-3 ways you can bind css class to angular components.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With