Introduction to Angular ngClass and ngStyle
Creating dynamic styles in web applications can be a real pain. Luckily with Angular we have multiple ways to handle our dynamic CSS and CSS classes with the new template syntax as well as some built in directives.
Angular Template Property Syntax
First lets look at how we would change a <div>
color property in pure JavaScript.
let myDiv = document.getElementById('my-div');
myDiv.style.color = 'orange'; // updating the div via its properties
Now lets look at the primitives the Angular syntax gives us out of the box.Using the [property]
syntax we can easily access any element or component properties.
<div [style.color]="'orange'">
style using property syntax, this text is orange
</div>
In the example above we can directly access the style property of our div element. This is different than an attribute. Properties are the properties defined on our DOM object just like the one we updated in our first example with just plain JavaScript.
We can also use the Angular property syntax to add CSS classes to elements.
<div [className]="'blue'">
CSS class using property syntax, this text is blue
</div>
ngStyle and ngClass
Out of the box with the new syntax we don't need special ng-class
or ng-style
directives like in Angular 1. But with Angular we still have these built in directives. These directives offer syntactic sugar for more complex ways of altering our element styles. First lets look at ngStyle
.
<div [ngStyle]="{'color': 'blue', 'font-size': '24px', 'font-weight': 'bold'}">
style using ngStyle
</div>
In this example using ngStyle
we can easily style multiple properties of our element. We also can bind these properties to values that can be updated by the user or our components.
<div [ngStyle]="{'color': color, 'font-size': size, 'font-weight': 'bold'}">
style using ngStyle
</div>
<input [(ngModel)]="color" />
<button (click)="size = size + 1">+</button>
<button (click)="size = size - 1">-</button>
Next lets look at the ngClass
directive and the options it provides to update classes on our components and HTML elements.
<div [ngClass]="['bold-text', 'green']">array of classes</div>
<div [ngClass]="'italic-text blue'">string of classes</div>
<div [ngClass]="{'small-text': true, 'red': true}">object of classes</div>
Same as ngStyle
the ngClass
allows multiple ways to add and toggle our CSS. We can bind these classes directly to our component properties to update them dynamically as needed. Between the new template syntax and a few more directives our Angular apps are easier than ever to style. Checkout the work demo below!