NgClass class

The NgClass directive conditionally adds and removes CSS classes on an HTML element based on an expression's evaluation result.

The result of an expression evaluation is interpreted differently depending on type of the expression evaluation result:

  • String - all the CSS classes listed in a string (space delimited) are added
  • List - all the CSS classes (List elements) are added
  • Object - each key corresponds to a CSS class name while values are interpreted as expressions evaluating to bool. If a given expression evaluates to true a corresponding CSS class is added - otherwise it is removed.

While the NgClass directive can interpret expressions evaluating to String, Array or Object, the Object-based version is the most often used and has an advantage of keeping all the CSS class names in a template.

Examples

<div [ngClass]="currentClasses">This div is initially saveable, unchanged, and special</div>
Map<String, bool> currentClasses = <String, bool>{};
void setCurrentClasses() {
  currentClasses = <String, bool>{
    'saveable': canSave,
    'modified': !isUnchanged,
    'special': isSpecial
  };
}

Try the live example. For details, see the ngClass discussion in the Template Syntax page.

Implemented types
Annotations

Constructors

NgClass(Element _ngEl)

Properties

hashCode int
The hash code for this object.
no setterinherited
initialClasses String?
no getter
rawClass Object?
no getter
runtimeType Type
A representation of the runtime type of the object.
no setterinherited

Methods

ngDoCheck() → void
override
ngOnDestroy() → void
Executed before the directive is removed from the DOM and destroyed.
override
noSuchMethod(Invocation invocation) → dynamic
Invoked when a nonexistent method or property is accessed.
inherited
toString() String
A string representation of this object.
inherited

Operators

operator ==(Object other) bool
The equality operator.
inherited