本文介绍了Angular4-动态更改CSS类-哪个更好?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在本教程中,讲师提出了以下建议:

From the tutorial, instructor came up with this:

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

组件:

isFavorite = false;

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


而我的方式是:


While my way was:

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

组件:

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?

很抱歉,答案可能只是是".我只想确定它是如何工作的(尤其是对所有这些Ng指令感兴趣,例如ngModel,ngClass).

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).

谢谢

推荐答案

这当然是非常主观的,但是如果您担心性能,那么在这种特殊情况下,第一个可能会更快,因为编译器会创建以下精简函数来设置类:

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);
        ...
    });

_ck函数最终将为每个类调用renderer.setElementClass.要了解有关updateRenderer函数的更多信息,请阅读 DOM更新机制在Angular 中,尤其是在Update renderer部分中.

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.

ngClass的耗时检查过程与众不同:

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);
      }
    }
  }

但是,ngClass具有更丰富的功能,因此比较它们的性能是不公平的.

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

这篇关于Angular4-动态更改CSS类-哪个更好?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-22 13:06