What is the purpose of ng-class in Angular?

In Angular, the ng-class directive is used to dynamically set an element’s class based on conditions. Its purpose is to toggle the class of an element based on the value of an expression.

The ng-class directive can be used in several ways:

  1. Object syntax: You can pass an object and switch classes based on the object’s property values. For example, ng-class=”{ ‘active’: isActive }”, if isActive is true, the element will have the active class.
  2. Array syntax: You can pass an array to dynamically add or remove classes based on each element in the array. For example, ng-class=”[ ‘red’, ‘bold’ ]” will give the element both the red and bold classes at the same time.
  3. Expression syntax: You can pass an expression to switch classes based on the value of the expression. For example, ng-class=”isActive ? ‘active’ : ‘inactive'” will apply the ‘active’ class if isActive is true, and the ‘inactive’ class if it is false.

By using the ng-class directive, you can dynamically change the style of an element based on conditions, achieving more flexible interface interaction effects.

bannerAds