NgStyle class

The NgStyle directive changes an element's style based on the bound style expression:

<div [ngStyle]="styleExp"></div>

styleExp must evaluate to a Map<String, String>. Element style properties are set based on the map entries: each key:value pair identifies a style property name and its value.

For details, see the ngStyle discussion in the Template Syntax page.

Examples

Try the live example from the Template Syntax page. Here are the relevant excerpts from the example's template and the corresponding component class:

<div [ngStyle]="currentStyles">
  This div is initially italic, normal weight, and extra large (24px).
</div>
Map<String, String> currentStyles = <String, String>{};
void setCurrentStyles() {
  currentStyles = <String, String>{
    'font-style': canSave ? 'italic' : 'normal',
    'font-weight': !isUnchanged ? 'bold' : 'normal',
    'font-size': isSpecial ? '24px' : '12px'
  };
}

In this example, user changes to the <input> elements result in updates to the corresponding style properties of the first paragraph.

A Map literal can be used as a style expression:

<div [ngStyle]="{'font-style': 'italic'}"></div>

A better practice, however, is to bind to a component field or method, as in the binding to setStyle() above.

Implemented types
Annotations

Constructors

NgStyle(Element _ngElement)

Properties

hashCode int
The hash code for this object.
no setterinherited
rawStyle Map<String, String?>?
no getter
runtimeType Type
A representation of the runtime type of the object.
no setterinherited

Methods

ngDoCheck() → void
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