ngClass with Angular 2 and TypeScript - Loading..
Style: Blog or IDE

ngClass with Angular 2 and TypeScript

ngClass adds and removes CSS classes on an element. An [ngClass] directive (in square brackets) uses the results of a template expression (in quotes) to set the names of the classes.

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


In the first example on the left, a space-separated list of CSS class names in the myClasses variable is added to the existing classes on the element when the buttons are clicked. An array of class names is also valid.

The second example uses a key:value control object to set the classes. If the big variable (the value) is true then the 'big' class (the key) is added to the element. If the back variable is true then the 'bright' class is added to the element, and so on. This allows multiple classes to be added and removed using a single ngClass directive.

We can also use a class binding to set a specific class name if the template expression in quotes is truthy.

ng-class.component.ts x

The Application

You can give it a try here.


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.
  • ngStyle sets CSS styles on an HTML element conditionally.