Open In App

Signals in Angular

Last Updated : 03 Sep, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Signals are a reactive data model that provides a simple way to manage and track changes in state within an application. A Signal in Angular is a variable whose value can change over time and any change to this value will automatically propagate to the parts of the application that depend on it.

Key Concepts

  1. Signals: A reactive primitive that holds a value and notifies subscribers when the value changes.
  2. Effects: Functions that automatically re-run when the signals they depend on change effects can be used to trigger side effects based on signal changes.
  3. Signal Equality Functions: These are functions that compare the new values of a signal to its previous value to determine whether an update should trigger a re-run or effects or re-rendering.
  4. Effect Cleanup Functions: Functions that are called to clean up any side effects or resources when an effect re-runs or when the component is destroyed.

Prerequisites

To understand this article you have basic knowledge in the below listed topics.

Here we provide a list possible Approaches for creating Signals in Angular framework.

Creating Signals using the signal function

The signal function is used to create a reactive data source. This data source can be used in templates or component logic and It automatically updates whenever the signals value changes.

Syntax

const mySignal = signal(initialValue);

Example

import { signal } from '@angular/core';

const counterSignal = signal(0);

// Increment the counter
counterSignal.update(count => count + 1);

// Get the current value
console.log(counterSignal()); // Outputs: 1
  • signal (initialValue): Creates a new signal with an initial value.
  • counterSignal.update (fn): Updates the signal using the provided function.
  • counterSignal(): Retrieves the current value of the signal.

Creating Computed Signals using the computed function

The computed function is used to create a signal that delivers its value other signals and It automatically recalculates whenever any of the dependent signals change.

Syntax

const myComputedSignal = computed(() => /* expression based on other signals */);

Example

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

const x = signal(2);
const y = signal(3);

const sum = computed(() => x() + y());

console.log(sum()); // Outputs: 5

// Update one of the signals
x.set(5);

console.log(sum()); // Outputs: 8 (since x is now 5 and y is 3)
  • computed(() => /* expression */): Creates a computed signal based on other signals.
  • sum(): Retrieves the current computed value, which is automatically updated when x or y changes.

Using Effects

Effect functions are a way to watch for changes in signals and trigger specific code when those changes occur. An effect is automatically re run whenever any signal it depends on changes.

Example

import { effect, signal } from '@angular/core';

const count = signal(0);

// Define an effect that logs the count whenever it changes
effect(() => {
console.log(`Count changed to: ${count()}`);
});

// Update the signal value
count.set(1); // Logs: "Count changed to: 1"

Signal Equality Functions

These functions are used to optimize reactivity by determining if the value of a signal has actually changed. If the equality function returns false angular can avoid unnecessary updates.

Example

import { signal, signalEquality } from '@angular/core';

const mySignal = signal({ x: 10, y: 20 }, { equals: (a, b) => a.x === b.x && a.y === b.y });

mySignal.set({ x: 10, y: 20 }); // No effect triggered, as the values are considered equal
mySignal.set({ x: 15, y: 20 }); // Effect triggered, as the x value has changed

Effect Cleanup Functions

When an effect function is re run due to a change in one of its signals a cleanup function can be used to clean up resources or side effects from the previous run before the new effect is executed.

Example:

import { effect, signal } from '@angular/core';

const count = signal(0);

effect((onCleanup) => {
const interval = setInterval(() => {
console.log(`Interval count: ${count()}`);
}, 1000);

// Define the cleanup function to clear the interval
onCleanup(() => clearInterval(interval));
});

count.set(1); // Triggers re-run, and the old interval is cleared

Steps to Create Angular Application

Here we first created a new angular application once project is created successfully then we develop logic for signals. For achieving Signals in Angular follow below step by step process.

Step 1 : Create a New Angular Application

First create a new Angular Application by using below command. Once project is created navigate to project folder.

ng new angular-signals-demo
cd angular-signals-demo
Screenshot-2024-08-23-155015
Folder Structure

Step 2 : Update the Application to Use Signals

Signals are part of the Angular core, so no additional modules need to be installed. You can directly use the signal and computed functions.

Step 3: Implement Signals in Application

To implement signals in our application we need to change below listed files in the project folder.

HTML
<!-- src/app/app.component.html -->

<h1>Angular Signals Example</h1>
<p>Counter: {{ counter() }}</p>
<button (click)="increment()">Increment</button>
<p>Double: {{ doubleCounter() }}</p>
CSS
/* src/app/app.component.css */

h1 {
    color: #333;
}

button {
    margin-top: 10px;
}
JavaScript
// src/app/app.component.ts

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

@Component({
    selector: 'app-root',
    standalone: true, // This ensures the component is standalone
    templateUrl: './app.component.html', // External template file
    styleUrls: ['./app.component.css'] // External stylesheet file
})
export class AppComponent {
    // Define signals
    counter = signal(0);
    doubleCounter = computed(() => this.counter() * 2);

    // Method to increment the counter
    increment() {
        this.counter.update(count => count + 1);
    }
}

Step 4: Run the Application

Once development is completed now run the angular application by using below command.

ng serve

Output

Once project is successfully running now test the application. When you run this application. The UI will display the initial counter value which is 0 when you click on the increment button the counter will increate by 1 and the double counter value updated automatically to reflect twice the value of the counter.


Next Article
Article Tags :

Similar Reads