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.

See the Template Syntax section on NgStyle for more details.

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> <p [ngStyle]="setStyle()" #styleP>Change style of this text!</p> <label>Italic: <input type="checkbox" [(ngModel)]="isItalic"></label> | <label>Bold: <input type="checkbox" [(ngModel)]="isBold"></label> | <label>Size: <input type="text" [(ngModel)]="fontSize"></label> <p>Style set to: <code>'{{styleP.style.cssText}}'</code></p> </div>

bool isItalic = false; bool isBold = false; String fontSize = 'large'; Map<String, String> setStyle() { return { 'font-style': isItalic ? 'italic' : 'normal', 'font-weight': isBold ? 'bold' : 'normal', 'font-size': fontSize }; }

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
  • DoCheck
Annotations
  • Directive(selector: "[ngStyle]", inputs: const ["rawStyle: ngStyle"])

Constructors

NgStyle(KeyValueDiffers _differs, ElementRef elementRef)

Properties

hashCode → int

Get a hash code for this object.

read-only, inherited
rawStyle → Map<String, String>

write-only
runtimeType → Type

A representation of the runtime type of the object.

read-only, inherited

Operators

operator ==(other) → bool

The equality operator.

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