Angular 8 NgStyle Directive
Angular 8 NgStyle Directive
The ngStyle attribute is used to change and style the multiple properties of Angular. We can change the value, color, and size, etc. of the component. It is a built-in directive, ngStyle, to modify a component or element’s style attribute.
It acts the same as the component attribute bindings. The ngStyle directive specifies the style attribute for the HTML element. The value of the ngStyle quality must be an object, or an expression returning an object.
The object consists of CSS properties and values in key-value pairs.
Syntax:
Example:
Using an object with CSS keys and values;
Welcome
How to apply CSS classes dynamically with ng-Class
In the previous article, we have to seen that how to use ngClass directive to apply a CSS class to the element. It facilitates us to add or remove a CSS dynamically.
Create a class in the component.ts file, which will change the color of the text yellow if the server is online.
component.ts file:
import {Component} from '@angular/core'; @Component( {selector: 'app-server', templateUrl: 'server.component.html', styles: [` .Online{ color: yellow; }`] }) export class ServerComponent { serverID: number = 10; serverStatus: string = 'Offline'; constructor () { this.serverStatus = Math.random() > 0.5 ? 'Online' : 'Offline'; } getServerStatus() { return this.serverStatus; } getColor() { return this.serverStatus === 'Online' ? 'green' : 'red'; } }
Component.html file:
Server with ID {{serverID}} is {{serverStatus}}.
Output:
