Sub topic 12
Outputs and RxJS
This chapter assumes you know output() and emit(), how a parent listens with (event)="handler($event)", and the basics of RxJS (Subject, pipe, subscribe). Signals are not needed here. RxJS is only the bridge between an observable stream and an output.
Why connect outputs to RxJS
An output() is not an observable. It is an OutputEmitterRef with emit() and subscribe() methods, and it has no pipe(). That is usually what you want, because most events are single clicks or selections that need no stream operators.
Some events are streams: keystrokes that need debouncing, websocket messages, or a chain of switchMap calls. If you build the stream with RxJS inside the child, you need a way to publish the result as an output. If you consume an output in code that already uses RxJS, you need the opposite conversion. The package @angular/core/rxjs-interop provides one function for each direction:
| Direction | Function | Input | Result |
|---|---|---|---|
| Observable to output | `outputFromObservable()` | An `Observable<T>` | An output that emits `T` |
| Output to observable | `outputToObservable()` | An `OutputRef<T>` | An `Observable<T>` |
Publishing an observable as an output
outputFromObservable() takes an observable and returns an output. A search box shows why this is useful. Without it, you would subscribe to the pipeline yourself and call emit() in the callback, and you would have to clean up the subscription.
import { Component } from '@angular/core';
import { outputFromObservable } from '@angular/core/rxjs-interop';
import { Subject, debounceTime, distinctUntilChanged } from 'rxjs';
@Component({
selector: 'app-search-box',
template: `<input type="search" (input)="onInput($event)" />`,
})
export class SearchBox {
private query$ = new Subject<string>();
queryChanged = outputFromObservable(
this.query$.pipe(debounceTime(300), distinctUntilChanged())
);
onInput(event: Event) {
this.query$.next((event.target as HTMLInputElement).value);
}
}The parent sees an ordinary output:
<app-search-box (queryChanged)="search($event)" />The parent cannot tell whether queryChanged came from output() or from an observable. It receives the debounced string in $event.
What Angular does for you
- It subscribes to the observable for you and forwards each emitted value to the parent's listeners.
- It unsubscribes when the component is destroyed, so you need no
ngOnDestroyortakeUntil. - It takes the output name from the class field, here
queryChanged, the same as withoutput().
Rules to remember
- Call it in an injection context. A field initializer is the normal place. Calling it inside a method fails at runtime.
- Assign the result to a class field. The Angular compiler finds outputs by looking for these calls in field initializers. A call in a local variable is not recognized as an output.
- Declare the source observable before the output field. Class fields initialize in order, so
query$must be defined abovequeryChanged. If it is defined below,this.query$isundefinedwhen the pipe runs. - Pass options as a second argument. You can alias the output, as with
output():
queryChanged = outputFromObservable(this.query$, { alias: 'search' });The parent then writes (search)="...".
Observable or plain `output()`?
Use outputFromObservable() when the value is already the result of a pipeline. Use plain output() with emit() when the event comes from a single method call, such as a click handler. Wrapping a click in a Subject only to expose it as an output adds code without adding behavior.
The example above could be written with output<string>() and a setTimeout for debouncing. The RxJS version is shorter and handles cancellation correctly, because debounceTime drops the earlier value when a new one arrives.
Turning an output into an observable
outputToObservable() goes the other way. It takes any OutputRef, such as an output() field on a child, and returns an Observable. Use it when the consumer is RxJS code, for example to combine several child events with merge or switchMap.
This example assumes a Counter component like the one in the earlier chapter, with changed = output<number>(), in ./counter:
import { AfterViewInit, Component, viewChild } from '@angular/core';
import { outputToObservable } from '@angular/core/rxjs-interop';
import { map } from 'rxjs';
import { Counter } from './counter';
@Component({
selector: 'app-dashboard',
imports: [Counter],
template: `
<app-counter [step]="2" />
<p>Scaled value: {{ scaled }}</p>
`,
})
export class Dashboard implements AfterViewInit {
private counter = viewChild.required(Counter);
scaled = 0;
ngAfterViewInit() {
outputToObservable(this.counter().changed)
.pipe(map((count) => count * 10))
.subscribe((value) => (this.scaled = value));
}
}Three details matter here.
- The
viewChildquery resolves after the view is created, so the earliest safe place to read it isngAfterViewInit. Reading it in the constructor throws. - The returned observable completes when the child component is destroyed. That is why this example needs no manual unsubscribe: the child's destruction ends the stream and releases the subscription.
- Only subscribe to a child's output this way when you hold a reference to the child. In a template you should still use
(changed)="...", which is simpler and needs no references.
Subscribing without RxJS
You do not always need outputToObservable(). An output ref has its own subscribe() method, which returns an object with unsubscribe():
const subscription = this.counter().changed.subscribe((count) => {
console.log('Count is now', count);
});
// later, if you need to stop early
subscription.unsubscribe();This is handy for a single listener. Move to outputToObservable() when you want operators.
Choosing a strategy
| Situation | Use |
|---|---|
| One event per user action (click, submit) | `output()` and `emit()` |
| Value comes from an existing observable pipeline | `outputFromObservable()` |
| Debounce, throttle, or retry before notifying the parent | `outputFromObservable()` |
| Combine several child outputs with RxJS operators | `outputToObservable()` |
| One simple listener in TypeScript code | `output.subscribe()` |
Relation to `EventEmitter`
Older components used @Output() changed = new EventEmitter<T>(). EventEmitter extends RxJS Subject, so you could call pipe() on it. People often abused this by subscribing to their own emitters.
output() removed that. It is not an observable, so you cannot pipe it inside the child, and the conversion functions make the move to RxJS explicit. If you are migrating code that relies on EventEmitter being a subject, keep the subject as a private field and expose it with outputFromObservable().
Common mistakes
- Calling
outputFromObservable()in a method or after construction. It needs an injection context and a field initializer. - Declaring the output field above its source. The pipeline is built with
undefined, which throws at construction. - Forgetting that errors end the stream. Add
catchErrorupstream. - Reading a
viewChildtoo early. UsengAfterViewInitor aneffect/afterNextRendercallback, not the constructor. - Emitting through a subject that is never given values. If nothing calls
next(), the parent never gets an event. Check that your DOM handler actually feeds the subject.
Exercise
A child component declares results = outputFromObservable(this.results$); as its first field, and private results$ = new Subject<string[]>(); as its second field. What goes wrong, and how do you fix it?
Show answer
Class fields initialize in the order they are written, so this.results$ is still undefined when outputFromObservable() runs, and the component fails at construction. Move the results$ declaration above the results field so the Subject exists before the output is created.
Exercise
You want a SearchBox that tells the parent about the search text at most once every 400 ms, ignores repeated identical values, and does not leak subscriptions. Which function do you use, and which operators belong in the pipeline?
Show answer
Use outputFromObservable() on a pipeline built from a Subject<string>: query$.pipe(debounceTime(400), distinctUntilChanged()). Angular subscribes for you and unsubscribes when the component is destroyed, so no takeUntil or ngOnDestroy is needed.
Exercise
A parent component holds a child through viewChild.required(Counter) and wants to apply map() to the child's changed output. Why can't it call this.counter().changed.pipe(...) directly, and where should it do the conversion?
Show answer
An output() field is an OutputEmitterRef, not an observable, so it has no pipe(). Wrap it with outputToObservable(this.counter().changed), and do this in ngAfterViewInit or later, because the viewChild query is not resolved in the constructor.