When you develop Angular apps, you'll find that you may want to alter the appearance of certain HTML elements based on certain conditions that occur. The way you handle these situations is through class binding and style binding. But first, if you prefer to watch a video tutorial on this subject:

A Quick Note There are 2 methods of class and style binding. One method is based on changing a single class or style, while the other is based on changing multiple classes or styles. First, we'll tackle the easier of the two, which is changing a single property.

Class Binding (Changing a Single Class) Changing a single class is fairly straight forward. We first have to attach the class prefix along with the associated class name, to the HTML element(s) that we want to affect: import { Component } from '@angular/core'; @Component({ selector: 'my-app', template: ` <button class="my-btn" [class.extraclass]="someProperty">Call to Action</button> `, styles: [` .my-btn { font-size:1.7em; } .extraclass { background: black; color: white; } `] }) export class AppComponent { someProperty = true; } As shown above, we add class and then a . followed by the class name, to a given HTML element. Then Then we define the class name in the styles property of the Component metadata. And finally, we define the property of "someProperty" (you can name this whatever you like) in the component class. Typically, this property would be defined or not defined based on logic in your app.

Style Binding (Changing a Single Style) Changing a single style is very similar to the process of changing a single class. In fact, the only line that has to change is the HTML defining the button in the template property of the component metadata. //.. other code <button class="my-btn" [style.border]="someProperty ? '5px solid yellow' : 'none'">Call to Action 2</button> //.. other code

Changing Multiple Classes through Class Binding If you want to append or remove multiple classes through class binding, you have to use a different approach. You must use the NgClass directive. Here's how you use it: //.. component metadata <button class="my-btn" [ngClass]="setClasses()">Call to Action</button> , styles: [` .my-btn { font-size:1.7em; } .extraclass { background: black; color: white; } .anotherclass { font-weight:bold; } `] }) export class AppComponent { someProperty = true; anotherProperty = true; setClasses() { let classes = { extraclass: this.someProperty, anotherclass: this.anotherProperty, }; return classes; } } We attach the [ngClass] directive to the HTML element. Then we specify a method such as "setClasses()". We then must define this method in our app component. "extraclass" will be added to the classes attribute of the HTML element if this.someProperty is defined, and the same applies to the anotherclass CSS class. Note: You can also use !this.someProperty