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>
Angular ngStyle Directive – Objective Questions (MCQs)
Q1. ngStyle is used for:
Q2. ngStyle applies:
Q3. ngStyle works with:
Q4. ngStyle is an:
Q5. ngStyle is used when: