title: Angular 5 binding CSS classes: class, [class.foo], [ngClass]
body: <p>So I've been using Angular 5 for quite some time. And this question came to my mind: <strong>what is the best way to bind CSS classes to an element</strong>.</p>
  
  <ol>
  <li><h1><code>class="{{ foo }}"</code></h1>
  
  This way of binding gives us the opportunity to create CSS class name in <code>.ts</code> file, place the logic in <code>.ts</code> file, then use this given CSS class in HTML like this: <code>{{ foo }}</code>.</li>
  </ol>
  
  <p>Example:</p>
  
  <pre><code>// foo.component.ts
  ...
  export class FooComponent {
    someBool = true;
    foo = someBool ? 'error' : 'success'; // dummy logic
  }
  ...
  
  // foo.component.html
  ...
  &lt;div class="{{ foo }}"&gt;&lt;/div&gt;
  ...
  </code></pre>
  
  <ol start="2">
  <li><h1><code>[class.error]="foo"</code></h1>
  
  This way lets us use <code>.ts</code> variable to toggle specific CSS class</li>
  </ol>
  
  <p>Example:</p>
  
  <pre><code>// foo.component.ts
  ...
  export class FooComponent {
    someBool = true;
    foo = someBool; // dummy logic
  }
  ...
  
  // foo.component.html
  ...
  &lt;div [class.error]="foo"&gt;&lt;/div&gt;
  ...
  </code></pre>
  
  <ol start="3">
  <li><h1><code>[ngClass]="{'error': foo, 'success': !foo}"</code></h1>
  
  This one lets us add many CSS classes, imho it is the most readable one.</li>
  </ol>
  
  <p>Example:</p>
  
  <pre><code>// foo.component.ts
  ...
  export class FooComponent {
    someBool = true;
    foo = someBool; // dummy logic
  }
  ...
  
  // foo.component.html
  ...
  &lt;div [ngClass]="{'error': foo, 'success': !foo}"&gt;&lt;/div&gt;
  ...
  </code></pre>
  
  <hr>
  
  <p><strong>So let me know what, in your opinion, is the best way to do CSS classes binding. I know, there might be other ways to do so - let me know about them.</strong></p>