What is the usage of ng-class in Angular?
In Angular, the ng-class directive is used to dynamically set a element’s class based on conditions. It can accept an object, an array, a string, or a boolean value as a parameter.
- Object syntax: Using object syntax, determine which classes should be added or removed based on the key-value pairs of the object. For example:
- The text within the div will have different styles based on the isActive and isHighlighted variables.
- In the given example, if isActive is true, then add the class name “active”; if isHighlighted is true, then add the class name “highlight”.
- Array syntax: By using array syntax, it is possible to dynamically add or remove multiple classes when a condition is met. For example:
-
Some Text
- In the example above, if both activeClass and errorClass are string variables with the values “active” and “error”, then both classes will be added.
- String syntax: With the use of string syntax, you can either set a static class name or dynamically set a class name based on the result of an expression. For example:
- The text inside the div will be displayed as “Some Text” based on whether isActive is true or false, with the class ‘active’ or ‘inactive’ applied accordingly.
- In the example above, add the class “active” if isActive is true, otherwise add the class “inactive”.
- Boolean syntax: By using boolean syntax, you can dynamically add or remove a fixed class based on conditions. For example:
- A piece of text inside a
element will be styled as “active” if the isActive variable is true.
- In the example above, if isActive is true, then add the class name “active”.
ng-class also supports adding or removing multiple classes when conditions are met, or using expressions to dynamically set class names. This provides a flexible way to dynamically change the style of elements based on the application’s state.