<div> when isActive is true?<div [ngStyle]="{'background-color': isActive ? 'green' : 'red'}">Status Box</div>The ngStyle directive applies styles dynamically. Since isActive is true, the ternary expression sets the background color to green.
ngStyle in Angular?Option B correctly uses property binding with an object literal. The keys are strings for CSS properties, and the values are expressions. Other options have syntax errors or incorrect binding.
styles = { 'color': 'blue' };
updateColor() {
this.styles.color = 'red';
}And the template:
<div [ngStyle]="styles">Text</div>
Why might the color not change to red after calling
updateColor()?Angular's change detection checks object references. Mutating a property does not change the reference, so Angular may not detect the update. To fix, assign a new object.
isHighlighted = false;
getStyle() {
return {
'font-weight': this.isHighlighted ? 'bold' : 'normal',
'color': this.isHighlighted ? 'orange' : 'black'
};
}And template:
<button (click)="isHighlighted = !isHighlighted">Toggle</button> <span [ngStyle]="getStyle()">Text</span>
What will be the style of the
<span> after clicking the button once?Initially, isHighlighted is false, so styles are normal and black. After one click, it becomes true, so styles become bold and orange.
ngStyle for dynamic styling instead of directly binding to the style attribute like [style.color] or inline styles?ngStyle lets you apply many styles in one object, making templates cleaner and reducing multiple bindings. Other options are incorrect or false.