Performance: ngStyle for dynamic styles
ngStyle affects how styles are applied dynamically, impacting rendering speed and layout recalculations when styles change.
<div [style.width.px]="dynamicWidth" [style.height.px]="dynamicHeight" [style.margin.px]="dynamicMargin"></div>
<div [ngStyle]="{ 'width.px': dynamicWidth, 'height.px': dynamicHeight, 'margin.px': dynamicMargin }"></div>| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| ngStyle with many dynamic properties | Multiple style updates per change detection | Multiple reflows if layout styles change | High paint cost if many elements affected | [X] Bad |
| Individual style bindings for dynamic styles | Selective style updates | Reflows only when necessary | Lower paint cost | [OK] Good |
ngStyle do?ngStylengStyle is used to bind an object containing CSS styles to an element dynamically.ngClass which adds/removes classes, ngStyle directly sets inline styles.ngStyle in a template?ngStyle expects an object inside square brackets with key-value pairs for styles.color = 'blue';
isBold = true;
<div [ngStyle]="{'color': color, 'font-weight': isBold ? 'bold' : 'normal'}">Text</div>color is 'blue', so the style 'color' will be 'blue'.isBold is true, so the ternary expression returns 'bold'.<div [ngStyle]="{color: color, fontWeight: 'bold'}">Hello</div>color is a string variable in the component.fontWeight is camelCase and unquoted, which Angular does not convert automatically in ngStyle.isActive. Which ngStyle binding correctly applies a green background when active and gray when inactive?Pass the test and this pattern moves unknown