ngStyle lets you change CSS styles on HTML elements while your app runs. It helps make your page look different based on data or user actions.
0
0
ngStyle for dynamic styles in Angular
Introduction
You want to change the color of a button when a user clicks it.
You need to adjust the size of text based on user preferences.
You want to highlight a list item when it is selected.
You want to apply different background colors based on data values.
You want to show or hide styles dynamically without writing CSS classes.
Syntax
Angular
<element [ngStyle]="{ 'styleName': expression, 'anotherStyle': expression }"></element>Use square brackets [] to bind ngStyle to an object of style names and values.
Style names are strings and values can be variables or expressions.
Examples
This sets the text color to red and makes it bold.
Angular
<div [ngStyle]="{ 'color': 'red', 'font-weight': 'bold' }">Text</div>Here, font size changes based on the
fontSize variable in pixels.Angular
<p [ngStyle]="{ 'font-size.px': fontSize }">Resizable text</p>The button background changes color depending on
isActive.Angular
<button [ngStyle]="{ 'background-color': isActive ? 'green' : 'gray' }">Click me</button>Sample Program
This component shows a heading with color and size controlled by variables. Clicking the button toggles the color between blue and orange and the font size between 20px and 30px.
Angular
import { Component } from '@angular/core'; @Component({ selector: 'app-dynamic-style', template: ` <h2 [ngStyle]="{ color: titleColor, 'font-size.px': titleSize }">Dynamic Style Example</h2> <button (click)="changeStyle()">Change Style</button> ` }) export class DynamicStyleComponent { titleColor = 'blue'; titleSize = 20; changeStyle() { this.titleColor = this.titleColor === 'blue' ? 'orange' : 'blue'; this.titleSize = this.titleSize === 20 ? 30 : 20; } }
OutputSuccess
Important Notes
ngStyle works well for multiple style changes at once.
For single style changes, you can also use [style.styleName] binding.
Remember to use quotes around style names with dashes, like 'font-size.px'.
Summary
ngStyle binds an object of CSS styles to an element dynamically.
It helps change styles based on variables or expressions in your component.
Use it to make your app look interactive and responsive to user actions.