Understanding Angular Signals and Their Benefits

Aug 5, 2024

Angular Signals Lecture Notes

Introduction to Signals in Angular

  • Signals introduced in Angular v16, current version is v17.3.
  • Signals are becoming more integrated into Angular.
  • New API for component communication replacing old decorators like @Input, @Output, @ViewChild, etc.

Advantages of Signals

  • Performance Improvements: Applications may see significant performance improvements due to lightweight reactivity.
  • Improved Developer Experience: Error messages related to change detection reduced.
  • Future-Proofing: Less need to refactor code with upcoming Angular features.
  • Recommended Usage: Start using signals now despite being in developer preview.

Lecture Structure

  1. Basics of Signals
  2. Advanced Topics (e.g., ref, effect)
  3. Interoperability with RxJS
  4. New API with Signals

Change Detection in Angular

  • Angular uses Zone.js to manage change detection.
  • Change detection checks for property changes in components, starting from the root.
  • Signals improve change detection by being reactive data types that know their dependencies.

Implementing Signals

Creating Signals

  • Signals are created with the signal function, which requires an initial value.
  • Typescript infers types from the initial value.
  • Use set() or update() methods to modify signal values.

Accessing Signals

  • Access signal values by calling them like functions.
  • Signals are reactive; they will notify consumers of changes.

Reactivity and Templates

  • In templates, signals should be accessed in a reactive context.
  • Use computed functions for derived signals that react to changes in other signals.
  • Use effect functions for side effects based on signal changes.

Advanced Signal Usage

  • Dynamic Dependency Tracking: Signals automatically track dependencies; effects run based on current context.
  • Avoiding Infinite Loops: Angular prevents circular dependencies by default.
  • Untracked Functionality: Use untrack() to prevent unintended signal tracking in functions.

RxJS Interoperability

  • While signals are performant, RxJS may still have use cases, particularly in service logic.
  • Angular provides functions to convert between signals and observables:
    1. takeUntilDestroyed
    2. toSignal
    3. toObservable

New API for Component Communication

  • Replaces decorators with functions returning signals, improving clarity and usability.
  • Input and Output decorators are now functions that can provide signals.

Example: Input and Output in Components

  • Use input() for required input types.
  • Use output() for emitting events.
  • Supports two-way binding using model in the new API.

Conclusion

  • Signals are easy to use and enhance performance and developer experience.
  • Recommended to adopt signals progressively in existing codebases.
  • Further updates and features related to signals in Angular are anticipated.