*ngStyle directive
- The *ngStyle directive holds a unique place in the Angular world, enabling developers to dynamically apply styles to elements.
- This means that you can manipulate the appearance of elements based on specific conditions or user interactions.
Syntax:
<div [ngStyle]="{'property': 'value'}">Content</div>
Example:
Step 1: Create an Angular project using Angular CLI.
ng new ng-style-example
Step 2: Create a new component message
ng g c styling
Step 3: Edit the 'styling.component.html' to use '*ngStyle' :
<div>
<button [ngStyle]="buttonStyle" (click)="toggleStyle()">Click Me</button>
</div>
Step 4: Edit the 'styling.component.ts' to define the component's logic.
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() {
}
}
Step 5: Add the ‘<app-styling></app-styling>’ to the ‘app.component.html’ to include the ‘styling component’ in the main application.
<app-styling></app-styling>
Step 6: Now run or compile the application.
ng serve
You will see the result on http://localhost:4200