top of page
  • Writer's pictureCristian Duque

Angular Signals

Updated: Sep 1, 2023




Angular Signals is a recent feature starting from Angular version 16 that provides reactive primitives for Angular applications. It wraps a value and notifies consumers when the value changes. The signal values can either be primitives or complex data structures.


Signals are Reactive Primitives based on a pattern called Observer Design Pattern. According to this pattern, we have a Publisher that stores some value along with a list of Subscribers who are interested in it, and when the value changes, they receive a notification.


Angular Signals is a simpler and more straightforward approach than RxJS, but they are different: Signals are synchronous, while RxJS handles asynchronous operations as well.


A signal value is writable or read-only, and we can access the value using a getter function.

There are two types of signals:


1. Writable signal

To create one, use the signal(<value>) function to pass the initial value.


They provide an API with several functions to update the signal value:

With set(<value>), we can change the value of a signal.


The update function modifies the signal value through its current value:

Decrement signal value -> signal.update(x=> x-1);


To modify signal values containing objects, we can use the mutate function:

Update an array signal field -> signal.mutate(value => value[0].isActive = false);


asReadOnly() creates a read-only version of the signal, so it cannot be changed.



2. Computed Signal

It's a derived signal from other signals. It's a dependent, lazy signal that will be recomputed when the dependent signals are updated. These signals are memoised because once calculated, the signal value is cached to prevent recalculation.


Computed signals are not writable signals and can be dynamically created based on certain conditions:


If the isActive field in the dependent signal is false, the computed signal will be zero. Otherwise, the computed value from the dependent signal will be multiplied by 2.



Effects

They are operations that run whenever any signal value changes. Useful for logging, debugging or analytics purposes by tracking them.


Logging signal events on Console.


Check out my video:


6 views

Recent Posts

See All

Comments


bottom of page