Loading
*ngStyle directive
The *ngStyle directive in Angular helps you dynamically add or change CSS styles on an HTML element.
You can use it to update the look and feel of your app based on conditions, user clicks, or data without writing separate CSS classes.

It is like telling Angular:
If something changes, update these style properties automatically.



Syntax: 

<div [ngStyle]="{'property': 'value'}">Content</div>

You can

  • Apply multiple styles at once
  • Bind styles to variables or expressions
  • React to events like button clicks



Example: Using ngStyle in Angular


Step 1: Create a New Angular Project

ng new ng-style-example



Step 2: Generate a New Component

ng g c styling



Step 3: Add ngStyle in the Template

Edit styling.component.html

<div>
    <button [ngStyle]="buttonStyle" (click)="toggleStyle()">Click Me</button>
</div>

  • buttonStyle is a property we’ll define in TypeScript.
  • (click)="toggleStyle()" changes the style when the button is clicked.



Step 4: Define Logic in TypeScript

Edit styling.component.ts

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-styling',
  templateUrl: './styling.component.html',
  styleUrls: ['./styling.component.css']
})
export class StylingComponent implements OnInit {
  isClicked: boolean = false;

  get buttonStyle() {
    return this.isClicked
      ? { 'background-color': 'blue', color: 'white' }
      : { 'background-color': 'red', color: 'white' };
  }

  toggleStyle() {
    this.isClicked = !this.isClicked;
  }

  constructor() { }

  ngOnInit() { }
}

Here

  • The buttonStyle getter changes depending on isClicked.
  • Clicking the button toggles isClicked between true and false.



Step 5: Use the Component in the App

Edit app.component.html to include your new styling component

<app-styling></app-styling>



Step 6: Run the App

ng serve


Open your browser and go to: http://localhost:4200

You will see a button

  • Initially red background
  • Click to toggle to blue background
  • Click again to toggle back