MarkoCen / markocen.com

Personal website
http://www.markocen.com
1 stars 0 forks source link

What is Signals in Angular? #31

Open MarkoCen opened 1 year ago

MarkoCen commented 1 year ago

Signals in Angular are a new concept that is being introduced in Angular 16 or 17 as a simplified version of state management. They are designed to work seamlessly with BehaviorSubjects, NGRX, Observables, and Promises. Signals are meant to make working with state management easier and more efficient. They are integrated into the Angular Core and are expected to replace or extend NGRX. The implementation of Signals is currently in the testing phase and the API is not yet finalized.

Signals can be seen as a simpler version of Observables. They are designed to work flawlessly with Observables and can be used to simplify change detection. Signals are reactive and notify dependents whenever their value changes. They are a wrapper around a simple value and automatically update anything that uses them when their value changes.

The main difference between Signals and state is that Signals provide a simpler and more efficient way of managing state in Angular applications. They eliminate the need for complex state management libraries like NGRX and provide a more streamlined approach to handling state changes. Signals are designed to be side effect-free and to keep their dependents in sync.

Here is an example of how Signals can be used in an Angular component:

import { Component, computed, SettableSignal, signal, Signal } from '@angular/core';

@Component({
  selector: 'signal-test-component',
  template: '{{valueZ}}'
})
export class SignalTestComponent {
  public valueX: SettableSignal<number> = signal<number>(5);
  public valueY: SettableSignal<number> = signal<number>(5); 
  public valueZ: Signal<number>;

  constructor() {
    this.valueZ = computed(() => this.valueX() + this.valueY());
  }
}

In this example, valueZ is a Signal that depends on valueX and valueY. Whenever either valueX or valueY changes, valueZ will be automatically updated. Signals are immutable and do not have methods to update or mutate their value. This is the main difference between a SettableSignal and a Signal.

Pros of using Signals in Angular:

Cons of using Signals in Angular:

In conclusion, Signals in Angular are a new concept that simplifies state management and improves change detection. They are designed to work seamlessly with existing code and provide a more efficient way of managing state in Angular applications. While Signals are still in the testing phase and the API is not yet finalized, they show promise in improving performance and making state management easier in Angular.