Angular - 2.24-Dynamic styling of elements with ngStyle
In the previous lesson we discovered *ngIf, a structural directive that adds or removes elements from the DOM. We also mentioned another family of directives: attribute directives. They look like regular HTML attributes - they do not start with a star - and they enhance an existing element without changing the DOM structure. The first one we are going to use is ngStyle, which lets us set inline styles dynamically.
The goal is to colour a paragraph background based on the server status. ngStyle expects a JavaScript object whose keys are CSS properties (camelCase or kebab-case-in-quotes) and whose values are the corresponding string values. Because we want the value to be dynamic, we use property binding around the directive name: [ngStyle]. The whole thing reads <p [ngStyle]="{ backgroundColor: getColor() }">Server status</p>.
Compute the value in the class
- Add a method
getColor()that returns a string:return this.serverStatus === 'online' ? 'green' : 'red';. - The method runs on every change detection cycle, so the background updates whenever the status changes.
- You can pass multiple style properties at once:
{ backgroundColor: ..., color: ..., fontWeight: ... }.
Save the file and watch the paragraph: the background becomes green when the server is online and red otherwise. There is no extra logic in the template - we only describe how the style derives from data, and Angular keeps the DOM in sync.
Two important nuances to remember. First, directives such as ngStyle are attached as attributes, but the actual configuration happens through property binding ([ngStyle]). The square brackets are not part of the directive name itself - they belong to the binding syntax. Second, attribute directives like ngStyle never alter the DOM structure: they decorate an element that already exists. Once you grasp the distinction between directives, property binding and structural directives, the Angular template syntax becomes much easier to read.