ngStyle with Angular 2 and TypeScript - lishman.io
lishman.io Loading..
Style: Blog or IDE

ngStyle with Angular 2 and TypeScript

The ngStyle directive allows you to set CSS style on an HTML element conditionally.

Updated Jan 2017, Angular version 2.4.x

Quick Tip

In the text below, when you see a word or phrase with this color, click on it to highlight the source code.

Also, take a look at the IDE style to see this tutorial in wide-screen mode. You can always switch back using the Style link at the top of the page.

Show me the IDE style

Example

We can set inline styles dynamically with the ngStyle directive.

We bind the [ngStyle] directive in square brackets to a key:value control object in quotes. The style name in the key of the object is set to the corresponding value.

We can also use style binding to set a single style value. The template expression in quotes is evaluated and bound to the style in square brackets.

ng-style.component.ts x
Loading...

The Application

Here is the output from this component.

Loading...

Where Next?

More Directives

To learn more about the other built-in directives, take a look at these tutorials.

  • ngIf adds and removes elements in the DOM based on the results of an expression.
  • ngSwitch displays one element (and its children) from a set of possible options, based on some condition.
  • ngFor is a repeater directive which outputs a list of elements by iterating over an array.
  • ngClass adds and removes CSS classes on an element.