Angular Attribute Directives: ngClass and ngStyle
Unlike structural directives (which add/remove elements), attribute directives change the appearance or behavior of an element by modifying its attributes.
🎨 1. ngClass – Apply CSS Classes Dynamically
✅ Basic Usage:
<p [ngClass]="'highlight'">This is highlighted.</p>
✅ Conditional Class:
<p [ngClass]="{ 'active': isActive, 'error': hasError }">
Status Message
</p>
✅ Multiple Classes Based on Array:
<p [ngClass]="['base-class', dynamicClass]">Styled text</p>
🖌️ 2. ngStyle – Apply Inline Styles Dynamically
✅ Basic Usage:
<p [ngStyle]="{ 'color': 'blue', 'font-weight': 'bold' }">
Styled inline text
</p>
✅ Dynamic Style:
<p [ngStyle]="{ 'background-color': isError ? 'red' : 'green' }">
Conditional Background
</p>
✅ Using Component Properties:
In component.ts:
textColor = 'purple';
fontSize = '20px';
In template:
<p [ngStyle]="{ 'color': textColor, 'font-size': fontSize }">
Dynamic styles using component props
</p>
🧠Summary Table
| Directive | Purpose |
|---|---|
ngClass |
Dynamically add/remove CSS classes |
ngStyle |
Dynamically set inline styles |
Comments
Post a Comment