In Angular, ngStyle
is a directive that allows you to dynamically set inline styles for HTML elements. It’s a handy way to apply styles conditionally or based on some properties in your component class.
Here’s how you can use ngStyle
in Angular:
Template Syntax:
<div [ngStyle]="{'property': 'value', 'property2': 'value2'}">...</div>
Using Component Properties:
You can also bind styles based on properties from your component class:
<div [ngStyle]="myStyles">...</div>
export class MyComponent { myStyles = { 'color': 'blue', 'font-size': '16px' }; }
Conditional Styles:
<div [ngStyle]="{'background-color': isActive ? 'green' : 'red'}">...</div>
Object Syntax: in TypeScript file
export class MyComponent { fontSize = '14px'; fontWeight = 'bold'; }
<div [ngStyle]="{'font-size': fontSize, 'font-weight': fontWeight}">...</div>
Using Functions:
You can also use functions to dynamically generate styles:
export class MyComponent { getStyles() { return { 'color': this.isImportant ? 'red' : 'black', 'font-weight': this.isImportant ? 'bold' : 'normal' }; } }
<div [ngStyle]="getStyles()">...</div>