Course Progress 87%

Angular Signals

Angular Signals modern Angular का एक core reactive primitive है, जिसे fine-grained reactivity, better performance और simpler mental model के लिए introduce किया गया है। Signals का goal यह है कि UI state management easy, predictable और efficient बने, बिना RxJS की unnecessary complexity के।

इस chapter में हम Angular Signals को basic se लेकर advanced patterns तक detail में समझेंगे, ताकि आप production-grade applications में Signals confidently use कर सकें।

Signal क्या होता है

Signal एक reactive value होती है जो change होने पर automatically dependents को notify करती है।

count = signal(0);

यह normal variable जैसा दिखता है, लेकिन internally reactive होता है।

Value read करने के लिए function call किया जाता है:

count();

Signal Update कैसे होता है

Signal update करने के तीन main तरीके हैं।

count.set(5);
count.update(v => v + 1);
count.mutate(v => {
  // complex mutation (objects/arrays)
});

update() immutable update के लिए preferred है।

Signals क्यों लाए गए

RxJS powerful है, लेकिन UI state के लिए heavy हो सकता है।

Signals solve करते हैं:

  • Over-subscription problem
  • Manual unsubscribe
  • Unnecessary change detection
  • Complex syntax for simple state

Signals synchronous और deterministic होते हैं।

Signals और Change Detection

Signals Angular के change detection से tightly integrated हैं।

जब कोई signal change होता है:

  • Sirf वही template re-render होता है
  • Unrelated components untouched रहते हैं
  • Performance significantly improve होती है

यह fine-grained rendering कहलाता है।

Template में Signal Use करना

<p>{{ count() }}</p>
<button (click)="count.update(v => v + 1)">+</button>

No async pipe, no subscription, no boilerplate।

Computed Signals

Computed signals derived state represent करते हैं।

total = computed(() => this.count() * 2);

Rules:

  • Computed signal read-only होती है
  • Automatically dependencies track होती हैं
  • Lazy evaluation होता है

यह selectors का modern replacement है।

Computed Signal Example

price = signal(100);
quantity = signal(2);

totalPrice = computed(() => this.price() * this.quantity());

जब भी price या quantity change होगी, totalPrice auto-update होगा।

Effect क्या होता है

Effect side effects handle करने के लिए use होता है।

effect(() => {
  console.log(this.count());
});

जब भी count change होगा, effect re-run होगा।

Effects use करें:

  • Logging
  • LocalStorage sync
  • DOM interaction
  • Analytics

Business logic effects में मत डालो।

Effect Lifecycle

Effects:

  • Automatically run on dependency change
  • Auto-cleanup on destroy
  • Manual unsubscribe की जरूरत नहीं

यह RxJS subscriptions से ज्यादा safe है।

Writable vs Readonly Signals

Writable signal:

count = signal(0);

Readonly expose करना best practice है:

private _count = signal(0);
readonly count = this._count.asReadonly();

यह accidental mutation prevent करता है।

Signals के साथ Objects और Arrays

Signals immutable data के साथ best काम करते हैं।

users = signal<User[]>([]);

addUser(user: User) {
  this.users.update(list => [...list, user]);
}

Avoid करें direct mutation:

this.users().push(user); // गलत

Signal-based State Service

@Injectable({ providedIn: 'root' })
export class CounterState {
  private _count = signal(0);
  readonly count = this._count.asReadonly();

  increment() {
    this._count.update(v => v + 1);
  }
}

यह clean और scalable state pattern है।

Signals और Services

Signals services के अंदर state hold करने के लिए ideal हैं।

Benefits:

  • Centralized state
  • Reactive UI
  • Easy testing
  • No RxJS boilerplate

Modern Angular में यह default recommendation बन रहा है।

Signals + HTTP Integration

Signals खुद async handle नहीं करते, लेकिन async results store कर सकते हैं।

users = signal<User[]>([]);
loading = signal(false);

loadUsers() {
  this.loading.set(true);

  this.http.get<User[]>('/users').subscribe(data => {
    this.users.set(data);
    this.loading.set(false);
  });
}

RxJS async handle करता है, Signals UI state।

Signals vs Observables (Usage Perspective)

Signals:

  • UI state
  • Derived values
  • Local or shared state

Observables:

  • HTTP
  • Events
  • Streams over time

दोनों को mix करना best practice है।

Signals और Forms (Basic Pattern)

Forms के साथ signals UI sync के लिए use हो सकते हैं।

isValid = signal(false);

this.form.statusChanges.subscribe(status => {
  this.isValid.set(status === 'VALID');
});

Signals UI flags simplify करते हैं।

Zone-less Angular और Signals

Signals Angular को zone-less future की तरफ ले जाते हैं।

Advantages:

  • Manual change detection नहीं
  • Better performance
  • Predictable rendering

Signals future Angular architecture का key हिस्सा हैं।

Testing Signals

Signals test करना बहुत easy है।

state.increment();
expect(state.count()).toBe(1);

No async handling, no fakeAsync complexity।

Common Mistakes

  • Signals से async workflows बनाना
  • Heavy business logic effects में डालना
  • Direct mutation करना
  • RxJS को completely avoid करना

Signals RxJS का replacement नहीं हैं।

When Not to Use Signals

Avoid करें जब:

  • WebSocket streams हों
  • Complex async pipelines हों
  • Retry, debounce, cancelation चाहिए

इन cases में RxJS better है।

Best Practices

  • Signals UI state के लिए use करें
  • Computed for derived data
  • Effects minimal रखें
  • Immutable updates follow करें
  • Services में state encapsulate करें

Angular Signals modern Angular development का foundation बनते जा रहे हैं। सही तरीके से Signals use करने पर applications ज्यादा fast, predictable और maintainable बनती हैं। अगले chapter में हम Signals को performance model और advanced rendering behavior के साथ deep dive में explore करेंगे।