How to Create Signal in Angular: Simple Guide
In Angular, you create a signal using the
signal function from @angular/core. A signal holds reactive state and updates the UI automatically when its value changes.Syntax
Use the signal function to create a reactive signal. It takes an initial value and returns a signal object with a value property to get or set the current state.
signal(initialValue): Creates a new signal with the given initial value.signal.value: Access or update the signal's current value.
typescript
import { signal } from '@angular/core'; const count = signal(0); // Read value console.log(count.value); // Update value count.value = 5;
Output
0
Example
This example shows a simple Angular component using a signal to track a counter. The UI updates automatically when the signal changes.
typescript
import { Component, signal } from '@angular/core'; @Component({ selector: 'app-counter', template: ` <h1>Counter: {{ count() }}</h1> <button (click)="increment()">Increment</button> ` }) export class CounterComponent { count = signal(0); increment() { this.count.value += 1; } }
Output
Counter: 0 (initially)
After clicking 'Increment' button, the number increases by 1 each time.
Common Pitfalls
Common mistakes when using signals include:
- Trying to update the signal by calling it like a function instead of setting
value. - Not using the signal as a function in templates to get its current value.
- Mutating objects inside signals directly instead of replacing them.
Always update signals by assigning to value and read them in templates by calling the signal as a function.
typescript
/* Wrong way: */ count(5); // ❌ This does not update the signal /* Right way: */ count.value = 5; // ✅ Correct way to update /* In template, use: */ {{ count() }} <!-- Correct to get current value -->
Quick Reference
Summary tips for using signals in Angular:
- Import
signalfrom@angular/core. - Create signals with an initial value:
const mySignal = signal(initialValue); - Read signal value in code with
mySignal.valueor in templates with{{ mySignal() }}. - Update signal value by assigning to
mySignal.value. - Use signals for simple reactive state without complex stores.
Key Takeaways
Create signals using the signal() function from @angular/core with an initial value.
Access or update signal state via the .value property in code.
Use signals as functions in templates to get their current value.
Always assign new values to signals instead of calling them to update.
Signals provide simple reactive state management in Angular components.