MyInternships.in

Directives, Pipes & Templates

Angular ngClass and ngStyle

ngClass applies CSS classes conditionally and ngStyle applies inline styles from a component expression. Both accept an object, and Angular also offers the lighter [class.x] and [style.prop] bindings for single values.


What is ngClass and ngStyle in Angular?

ngClass applies CSS classes conditionally and ngStyle applies inline styles from a component expression. Both accept an object, and Angular also offers the lighter [class.x] and [style.prop] bindings for single values.

ngClass and ngStyle example

Conditional classes and styles
HTML
<!-- object form: key = class name, value = condition -->
<div [ngClass]="{ featured: job.isPromoted, expired: job.isClosed }">…</div>

<!-- single class — lighter and preferred -->
<div [class.featured]="job.isPromoted">…</div>

<!-- styles -->
<div [ngStyle]="{ 'background-color': job.color, width: pct + '%' }">…</div>
<div [style.width.%]="pct">…</div>

Key points to remember

  • Prefer [class.x] and [style.prop] for a single value — they are faster and clearer.
  • ngClass also accepts a string or an array of class names.
  • The .unit suffix on style bindings lets you bind a plain number.

Common mistakes with ngClass and ngStyle

  • Building the ngClass object inline in the template, creating a new object on every change detection cycle.
  • Using inline styles where a class would be more maintainable.

Angular ngClass and ngStyle— Interview Questions & FAQs

ngClass or class binding?+

Use [class.name]="condition" for one class — it is simpler and faster. Use [ngClass] when several classes are decided together by one expression.

Related Angular Topics

Keep learning with these closely related lessons.

Ready to use your Angular skills?

Find verified Angular internships and fresher developer jobs across India.

Browse Angular Internships