ngStyle Directive

  • ngStyle is a attribute directive
  • Unlike Structural directive, attribute directive does not add or remove elements but only change the elements they are placed on.

Lets create a new angular project using angular CLI and make below changes in app.component.html file

<H3>Change Button color</H3>
<button (click)="onButtonClick()" [ngStyle]="{backgroundColor : myColor}">Change Color</button>

Make the below changes in app.component.ts file

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'ngIfElseDemo';
  myColor = 'green';
  onButtonClick(){
    this.myColor = Math.random() > 0.5 ? 'pink' : 'yellow';
  }
}

And the output will look like below :

Leave a Comment