Effects execute side-effects when signals change:
1import { effect, signal, inject, DestroyRef } from '@angular/core';
2
3@Component({...})
4export class LoggerComponent {
5 private destroyRef = inject(DestroyRef);
6
7 count = signal(0);
8 name = signal('Guest');
9
10 constructor() {
11 // Effect automatically tracks used signals
12 const logEffect = effect(() => {
13 console.log(\`Count changed to: \${this.count()}\`);
14 });
15
16 // Effect with cleanup
17 effect((onCleanup) => {
18 const timer = setInterval(() => {
19 console.log(\`Current count: \${this.count()}\`);
20 }, 1000);
21
22 onCleanup(() => {
23 clearInterval(timer);
24 });
25 });
26
27 // Manual effect destruction
28 this.destroyRef.onDestroy(() => {
29 logEffect.destroy();
30 });
31 }
32}1effect(() => {
2 // ...
3}, {
4 allowSignalWrites: true // Allows writing to signals inside the effect
5});✅ Good use cases:
❌ Avoid: