2

What will render faster?

  <div class="ololo" [ngClass]="{'my-class': myVar}">one</div>

or

  <div class="ololo {{myVar ? 'my-class': ''}}">another</div>

or some another way?

6
  • I think {{}} renders faster because of digest cycle. Commented Oct 6, 2017 at 12:04
  • I'm curious why this matters. My question is not snarky. If there's a use case for this then I want to know what it is. Commented Oct 6, 2017 at 12:06
  • 4
    @qiAlex Sounds like you're trying to become master of premature optimization ;p. There is no difference. Commented Oct 6, 2017 at 12:07
  • 1
    The second option will be faster because it will only change className property during change detection cycly while the first option will generate more code for NgClass directive and handle all hooks for this directive(especially ngDoCheck hook) Commented Oct 6, 2017 at 12:19
  • 3
    Actually I think you are right. Binding to class directly is a bad idea in general. This might cause issues here. [class.my-class]="myVar" would be the best option in my opinion. Commented Oct 6, 2017 at 12:20

1 Answer 1

6

I did some research and can surely say that this approach

<div class="ololo" [ngClass]="{'my-class': myVar}">one</div>

works about 3 times slower than

<div class="ololo {{myVar ? 'my-class': ''}}">another</div>

please see a demo

https://stackblitz.com/edit/angular-fvtzck

Sign up to request clarification or add additional context in comments.

3 Comments

It's 2.5 times faster on my machine.
can you explain why ngclass is slower ?
It must be slower, [ngClass] utilizes angular databinding and is dynamic in nature, class is compiled to html and is just running the code with raw js. The curiosity is more why it is so much slower.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.