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.

Implements
Annotations
  • @Directive(selector: '[ngClass]', inputs: const ['rawClass: ngClass', 'initialClasses: class'], visibility: Visibility.none)

Constructors

NgClass(Element _ngEl)

Properties

initialClasses String v
write-only
rawClass v
write-only
hashCode → int
The hash code for this object. [...]
read-only, inherited
runtimeType → Type
A representation of the runtime type of the object.
read-only, inherited

Methods

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

Operators

operator ==(other) → bool
The equality operator. [...]
inherited