Directives Overview
| Kind | Purpose | Examples |
| Component | A directive with a template | <app-card> |
| Structural | Add or remove elements | @if, @for (formerly *ngIf, *ngFor) |
| Attribute | Change look or behavior of an element | ngClass, ngStyle, your own appHighlight |
Class Bindings
Prefer simple bindings first:
html
<li [class.done]="todo.done">{{ todo.title }}</li>
<div [class]="isError ? 'alert alert-danger' : 'alert alert-info'">Message</div>
<div [class]="{ active: isActive, 'is-new': isNew }">Card</div>
ngClass still works for complex cases (arrays, objects, strings):
typescript
import { NgClass } from '@angular/common';
@Component({
selector: 'app-badge',
imports: [NgClass],
template: `<span [ngClass]="classes()">{{ status() }}</span>`,
})
export class Badge {
status = input('active');
classes = computed(() => ({
badge: true,
'bg-success': this.status() === 'active',
'bg-danger': this.status() === 'blocked',
}));
}
Style Bindings
html
<p [style.color]="color">Colored</p>
<div [style.width.%]="progress" [style.background-color]="'#0d6efd'">Bar</div>
<div [style]="{ 'font-size.px': size, fontWeight: 'bold' }">Text</div>
Use CSS classes for design: Put colors and spacing in CSS and let bindings switch classes on and off. Use style bindings only for values that change at run time, like a progress width.
NgOptimizedImage
Images are usually the biggest part of a page. **NgOptimizedImage** makes them load faster: lazy loading, correct sizes, preload hints and warnings about common mistakes.
typescript
import { NgOptimizedImage } from '@angular/common';
@Component({
selector: 'app-hero',
imports: [NgOptimizedImage],
template: `
<!-- main image at the top: load it first -->
<img ngSrc="hero.jpg" width="1200" height="600" priority alt="Mountain lake">
<!-- images lower on the page are lazy loaded automatically -->
<img ngSrc="team.jpg" width="400" height="300" alt="Our team">
<!-- fills its parent box -->
<div class="box" style="position: relative; height: 200px">
<img ngSrc="banner.jpg" fill alt="Banner">
</div>
`,
})
export class Hero {}
| Attribute | Meaning |
ngSrc | Use instead of src |
width, height | Required (avoids layout jumps). Or use fill |
priority | Mark the most important image (LCP) so it loads first |
placeholder | Show a blurry placeholder while loading (needs an image loader) |
alt | Always write meaningful alternative text |
Old Structural Directives
You will see these in older code. They still work and do the same as the new blocks.
html
<p *ngIf="user; else loginMsg">Hi {{ user.name }}</p>
<ng-template #loginMsg><p>Please log in</p></ng-template>
<li *ngFor="let item of items; trackBy: trackById">{{ item.name }}</li>
Conclusion
Use class and style bindings for dynamic looks, NgOptimizedImage for fast images and know the older *ngIf and *ngFor so you can read legacy code.
Quick Summary: [class.x], [style.x], ngSrc + width/height + priority.