What is Signal in Angular: Simple Explanation and Example
Signal in Angular is a reactive primitive that holds a value and notifies components when the value changes. It helps Angular apps update the UI efficiently by tracking dependencies and triggering updates automatically.How It Works
Think of a signal as a special box that holds a value. Whenever you change the value inside this box, Angular automatically knows which parts of your app depend on it and updates them. This is like having a smart assistant who watches your data and tells your UI to refresh only when needed.
This mechanism helps avoid unnecessary work and keeps your app fast and responsive. Instead of manually telling Angular to check for changes, signals do this for you by tracking who uses their value and notifying them on updates.
Example
This example shows how to create a signal, update its value, and display it in a component template.
import { Component, signal } from '@angular/core'; @Component({ selector: 'app-counter', template: ` <h1>Counter: {{ counter() }}</h1> <button (click)="increment()">Increment</button> ` }) export class CounterComponent { counter = signal(0); increment() { this.counter.set(this.counter() + 1); } }
When to Use
Use signal in Angular when you want simple and efficient reactive state management without complex setups. Signals are great for local component state, shared state between components, or any place where you want Angular to automatically update the UI when data changes.
For example, use signals to track user input, toggle UI elements, or manage counters and lists. They help keep your code clean and reactive without needing manual change detection calls.
Key Points
- Signals hold a value and notify dependents on change.
- They enable automatic UI updates without manual change detection.
- Signals simplify reactive programming in Angular.
- They are useful for local and shared state management.
- Signals improve app performance by updating only what changes.