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.

Implements
Annotations
  • @Directive(selector: '[ngStyle]', inputs: const ['rawStyle: ngStyle'], visibility: Visibility.none)

Constructors

NgStyle(Element _ngElement)

Properties

rawStyle Map<String, String> 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
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