BP169: Use ngClass/ngStyle instead of inline styles to reduce the number of DOM elements

Use ngClass/ngStyle instead of inline styles to reduce the number of DOM elements. Inline styles can make the HTML code difficult to read and maintain. Using ngClass/ngStyle allows you to apply styles conditionally based on data or user interactions. This can help reduce the number of DOM elements and improve performance.

For example, instead of using inline styles like this:

<div style="background-color: {{color}}; font-size: {{size}}px">
  This is some text.
</div>

You can use ngStyle like this:


<div [ngStyle]="{'background-color': color, 'font-size': size + 'px'}">
  This is some text.
</div>

Similarly, instead of using multiple classes with inline styles like this:

<div class="card" style="background-color: {{color}}; font-size: {{size}}px">
  <div class="card-header" style="background-color: {{headerColor}}; font-size: {{headerSize}}px">
    Card Header
  </div>
  <div class="card-body" style="background-color: {{bodyColor}}; font-size: {{bodySize}}px">
    Card Body
  </div>
</div>

You can use ngClass like this:

<div [ngClass]="['card', {'card-header': true, 'card-body': true}]" 
     [ngStyle]="{'background-color': color, 'font-size': size + 'px'}">
  <div [ngClass]="{'card-header': true}" 
       [ngStyle]="{'background-color': headerColor, 'font-size': headerSize + 'px'}">
    Card Header
  </div>
  <div [ngClass]="{'card-body': true}" 
       [ngStyle]="{'background-color': bodyColor, 'font-size': bodySize + 'px'}">
    Card Body
  </div>
</div>

Using ngClass/ngStyle can make the HTML code more readable and maintainable, and can also improve performance by reducing the number of DOM elements.

Download Better Coder application to your phone and get unlimited access to the collection of enterprise best practices.

Get it on Google Play