wasAsked.

what is angular signal? with the use ofangular signal can we replace observable?

EY · Role not specified · technical

Published

Year not specified · Angular

Community answers

Posted by wasAsked editorial collection

Signals are Angular's reactive primitive (introduced in Angular 16 and stable in later versions). A signal holds a value and notifies Angular precisely when that value changes, so only the affected parts of the UI update. Core API count = signal(0); // writable signal double = computed(() => this.count() * 2); // derived, cached, recalculates only when count changes constructor() { effect(() => console.log('Count is', this.count())); // side effect when dependencies change } increment() { this.count.update(c => c + 1); } // or this.count.set(5) In templates you read them by calling them: {{ count() }}. Related APIs: input(), output() and model() for component communication, viewChild() and contentChild() queries, linkedSignal for state that resets from a source, and resource() / httpResource() for loading async data into signals. Why signals matter - Fine-grained change detection: Angular knows exactly which components depend on which signals, enabling zoneless applications and better performance with OnPush. - Simpler state: no subscriptions to manage for synchronous state, and computed values are automatically memoised. Can signals replace Observables? Partly, but not completely. - Signals are great for synchronous state: UI state, form state, derived values, data already loaded into a store. Many uses of BehaviorSubject can become signals. - Observables remain better for asynchronous streams and events over time: HTTP requests, WebSockets, user input with debounceTime, combining and cancelling streams (switchMap, mergeMap, retry), and complex timing operators. - Signals always have a current value; Observables represent events that may or may not have occurred, and can complete or error. They work together through the rxjs-interop package: products = toSignal(this.http.get<Product[]>('/api/products'), { initialValue: [] }); search$ = toObservable(this.searchTerm); A good summary: use signals for state and Observables for async event streams, and convert between them where they meet.

Ravindra Wadile · · 0 likes

Sign in to add your answer

Related interview topics