5

From the tutorial, instructor came up with this:

<span class="glyphicon" [class.glyphicon-star-empty]="isFavorite" [class.glyphicon-star]="!isFavorite" (click)="toggleClass()"></span>

Component:

isFavorite = false;

toggleClass() {
 this.isFavorite != this.isFavorite;
}


While my way was:

<span class="glyphicon" [ngClass]="classes" (click)="toggleClasses()"></span>

Component:

classes = "glyphicon-star-empty";

toggleClasses() {
 this.classes == "glyphicon-star-empty"? this.classes = "glyphicon-star" : this.classes = "glyphicon-star-empty";
}

Both ways works as expected, but I feel my way is not very good from performance perspective because I am using a loop, right?

Sorry if answer might be simply "yes". I just want to be sure about how this works (especially interested in all those Ng directives, like ngModel, ngClass).

Thanks

2 Answers 2

12

Best way is to write it this way.

[ngClass]="{'class1': isFavorite, 'class2': !isFavorite}"

Like

<span class="glyphicon" [ngClass]="{'class1': isFavorite, 'class2': !isFavorite}" (click)="toggleClass()"></span>

Then you can bind toggleHandler

toggleClass() {
 this.isFavorite != this.isFavorite;
}
Sign up to request clarification or add additional context in comments.

1 Comment

Can you add a demo please?
3

This is of course very subjective, but if you're worried about performance, then in this particular case probably the first one will work faster because the compiler will create the following streamlined function to set the classes:

   function updateRenderer() {
        var _co = _v.component;
        var currVal_0 = _co.isFavorite;
        var currVal_1 = _co.isFavorite;
        _ck(_v, 0, 0, currVal_1, currVal_1);
        ...
    });

and _ck function will eventually call renderer.setElementClass for each class. To learn more about updateRenderer function read The mechanics of DOM updates in Angular, particularly Update renderer section.

While the ngClass goes through the time consuming process of checking the changes using differs:

  ngDoCheck(): void {
    if (this._iterableDiffer) {
      const iterableChanges = this._iterableDiffer.diff(this._rawClass as string[]);
      if (iterableChanges) {
        this._applyIterableChanges(iterableChanges);
      }
    } else if (this._keyValueDiffer) {
      const keyValueChanges = this._keyValueDiffer.diff(this._rawClass as{[k: string]: any});
      if (keyValueChanges) {
        this._applyKeyValueChanges(keyValueChanges);
      }
    }
  }

However, the ngClass has much richer functionality so it's not fair to compare their performance.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.