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.

  1. Object syntax: Using object syntax, determine which classes should be added or removed based on the key-value pairs of the object. For example:
  2. The text within the div will have different styles based on the isActive and isHighlighted variables.
  3. In the given example, if isActive is true, then add the class name “active”; if isHighlighted is true, then add the class name “highlight”.
  4. Array syntax: By using array syntax, it is possible to dynamically add or remove multiple classes when a condition is met. For example:
  5. Some Text
  6. In the example above, if both activeClass and errorClass are string variables with the values “active” and “error”, then both classes will be added.
  7. 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:
  8. 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.
  9. In the example above, add the class “active” if isActive is true, otherwise add the class “inactive”.
  10. Boolean syntax: By using boolean syntax, you can dynamically add or remove a fixed class based on conditions. For example:
  11. A piece of text inside a
    element will be styled as “active” if the isActive variable is true.
  12. 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.

Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds