Sobes.tech
Middle

Tell us about Angular Signals: signal, computed, effect — how do you use them in a component

sobes.tech AI

Answer from AI

In Angular Signals — this is a new reactive system for managing state and reacting to data changes.

  • signal — this is a reactive value that can be read and updated. When the value changes, all subscribers are automatically updated.

  • computed — this is a derived value that is calculated based on other signals and automatically updates when dependencies change.

  • effect — a function that executes when the signals it subscribes to change, usually for side effects (e.g., updating the DOM, calling an API).

Example of usage in a component:

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

@Component({
  selector: 'app-counter',
  template: `
    <button (click)="increment()">Increment</button>
    <p>Count: {{ count() }}</p>
    <p>Double: {{ doubleCount() }}</p>
  `
})
export class CounterComponent {
  count = signal(0); // initial state

  doubleCount = computed(() => this.count() * 2); // computed value

  constructor() {
    effect(() => {
      console.log('Count changed:', this.count()); // side effect on count change
    });
  }

  increment() {
    this.count.set(this.count() + 1);
  }
}

Here, count is a signal with state, doubleCount is a computed value depending on count, and effect reacts to changes in count, performing a side effect (logging). This approach simplifies state management and reactivity in Angular.