Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple classes in ngClass

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?

like image 618
Sagi Avatar asked Dec 29 '15 20:12

Sagi


People also ask

Can we add two classes in NgClass?

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.

Can we use multiple NgClass in angular?

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.

What is the difference between NgClass and class?

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.


1 Answers

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>
like image 96
Zyzle Avatar answered Sep 29 '22 21:09

Zyzle