Sub topic 8
Emitting Events with output()
Inputs carry data down from a parent to a child. Outputs carry notifications back up. This chapter covers output(), the function-based replacement for @Output() with EventEmitter. It explains how the returned object behaves, how parents listen to it in templates and in code, and how it connects to RxJS when you need stream operators.
This chapter assumes you know how to build Angular components with templates and event binding, and that you have read the chapters on signal inputs and model(). One section uses toObservable() and basic RxJS operators. The RxJS interop chapter covers those in depth.
The working model
An output is a named event that a component exposes. The child decides when the event happens and what value comes with it. The parent decides what to do about it. The child never calls the parent directly and does not need to know who is listening.
output<T>() returns an OutputEmitterRef<T>. That object has two methods you care about:
| Method | Who calls it | What it does |
|---|---|---|
| `emit(value: T)` | The child component | Notifies every current listener, synchronously, with `value` |
| `subscribe(fn)` | Angular, or your code for dynamic components | Registers a listener and returns a subscription with `unsubscribe()` |
An output is not a signal. It holds no current value and you cannot read it by calling it. It is a plain event channel. This matters because outputs often sit right next to input() and computed() fields that look the same at first glance. If you need the last emitted value as state, the parent should store it in a signal of its own.
Declaring and emitting outputs
Here is a todo item that reports two events: the user toggled it, and the user asked to delete it.
import { Component, input, output } from '@angular/core';
export interface Todo {
id: number;
title: string;
done: boolean;
}
@Component({
selector: 'app-todo-item',
template: `
<label>
<input type="checkbox" [checked]="todo().done" (change)="toggled.emit(todo().id)" />
{{ todo().title }}
</label>
<button (click)="requestDelete()">Delete</button>
`,
})
export class TodoItemComponent {
todo = input.required<Todo>();
toggled = output<number>();
deleted = output<void>();
requestDelete() {
if (confirm(`Delete "${this.todo().title}"?`)) {
this.deleted.emit();
}
}
}Several details are worth noting:
- The type argument sets the payload type.
emit()is type-checked against it, sothis.toggled.emit('3')fails to compile. output<void>()declares an event with no payload. You callemit()with no arguments.- You can emit straight from the template (
toggled.emit(todo().id)) or from a method. Use a method when the emit is conditional or needs logic, as with the confirmation inrequestDelete(). output()must be called in an injection context. In practice that means a field initializer, like every example here. Calling it inside a method or a lifecycle hook throws an error.
Listening from a parent template
The parent binds with the same parenthesis syntax used for DOM events. $event is the emitted value.
import { Component, signal } from '@angular/core';
import { Todo, TodoItemComponent } from './todo-item.component';
@Component({
selector: 'app-todo-list',
imports: [TodoItemComponent],
template: `
@for (todo of todos(); track todo.id) {
<app-todo-item
[todo]="todo"
(toggled)="toggle($event)"
(deleted)="remove(todo.id)"
/>
}
<p>{{ todos().length }} items</p>
`,
})
export class TodoListComponent {
todos = signal<Todo[]>([
{ id: 1, title: 'Write chapter', done: false },
{ id: 2, title: 'Review chapter', done: false },
]);
toggle(id: number) {
this.todos.update(list =>
list.map(t => (t.id === id ? { ...t, done: !t.done } : t))
);
}
remove(id: number) {
this.todos.update(list => list.filter(t => t.id !== id));
}
}The deleted handler ignores $event (it is undefined for a void output) and uses the loop variable instead. That works because the binding expression runs in the template scope of that loop iteration.
Notice where the state lives. The child does not change the todo. It reports intent, and the parent, which owns the todos signal, makes the change. This one-way flow is the main reason to use an output instead of model(). Use model() when parent and child share one value both ways. Use output() when the child reports something that happened and the parent decides how to respond.
Aliases and naming
You can expose an output under a different public name:
import { Component, output } from '@angular/core';
@Component({
selector: 'app-uploader',
template: `<button (click)="finished.emit('report.pdf')">Upload</button>`,
})
export class UploaderComponent {
finished = output<string>({ alias: 'uploadComplete' });
}The parent then writes (uploadComplete)="...", while the class still uses this.finished. Aliases are mainly useful for keeping a public name stable while you rename the class field. Most components should not need them.
Naming conventions from the Angular style guide:
- Name the event, not the handler:
deletedorvalueChange, notonDelete. - Do not reuse native DOM event names such as
click,change, orinput. Native events from inside the child can bubble up to the host element, so the parent's(click)handler may fire for both the DOM event and your output, with different$eventtypes.
Subscribing in code
Template binding covers most cases. When you create components dynamically, you subscribe yourself through the component instance:
import { Component, ViewContainerRef, inject } from '@angular/core';
import { TodoItemComponent } from './todo-item.component';
@Component({
selector: 'app-host',
template: `<button (click)="addItem()">Add item</button>`,
})
export class HostComponent {
private vcr = inject(ViewContainerRef);
addItem() {
const ref = this.vcr.createComponent(TodoItemComponent);
ref.setInput('todo', { id: 99, title: 'Dynamic', done: false });
const sub = ref.instance.toggled.subscribe(id => console.log('toggled', id));
ref.instance.deleted.subscribe(() => {
sub.unsubscribe();
ref.destroy();
});
}
}When the child component is destroyed, Angular cleans up every subscription to its outputs. You only need unsubscribe() when the listener should stop earlier than that. The explicit call in the example is only there to show the API.
Edge cases and gotchas
Emitting after destroy
An OutputEmitterRef belongs to its component's lifetime. If code emits after the component is destroyed, Angular raises a runtime error (NG0953) instead of silently doing nothing. This usually happens with a late async callback such as a setTimeout or an HTTP response that resolves after navigation. To fix it, cancel the async work on destroy, for example with DestroyRef.onDestroy() or takeUntilDestroyed().
Emits are synchronous
emit() calls each listener before it returns. If the parent's handler updates a signal, that update has happened by the time the next line in the child runs. The re-render does not happen during emit(). Angular schedules it the same way as any other signal change, which works with both OnPush and zoneless change detection.
Emitting from an effect
Calling emit() inside effect() is allowed. It is usually a design smell, though. An effect runs whenever its dependencies change, including on the first run. So the parent receives events that no user action caused. If the parent then writes back into an input the child reads, you can create a loop. Emit from event handlers. If a parent needs to follow a value continuously, consider model() instead.
No RxJS operators on the output itself
EventEmitter extended RxJS Subject, so people sometimes piped it or called next() on it. OutputEmitterRef is not an Observable. It has no pipe(), and subscribe() accepts only a function, not an observer object. The next section shows the supported bridge.
Bridging outputs and RxJS
@angular/core/rxjs-interop has two helpers:
outputFromObservable(obs$)declares an output whose events come from an Observable.outputToObservable(outputRef)turns any output into an Observable, which is useful when subscribing to a dynamic component's output with operators.
A search box that emits a debounced query:
import { Component, signal } from '@angular/core';
import { outputFromObservable, toObservable } from '@angular/core/rxjs-interop';
import { debounceTime, distinctUntilChanged } from 'rxjs';
@Component({
selector: 'app-search-box',
template: `<input [value]="query()" (input)="query.set($any($event.target).value)" />`,
})
export class SearchBoxComponent {
query = signal('');
search = outputFromObservable(
toObservable(this.query).pipe(debounceTime(300), distinctUntilChanged())
);
}The parent binds (search)="run($event)" exactly as it would bind any other output. A bridged output has no emit() method because the Observable is the only source of events. When the component is destroyed, Angular stops forwarding events from it.
Migrating from @Output() and EventEmitter
| Aspect | `@Output() x = new EventEmitter<T>()` | `x = output<T>()` |
|---|---|---|
| Declaration | Decorator plus class instance | Plain function call in an initializer |
| Emit | `emit()` (or `next()`) | `emit()` only |
| RxJS | Is a `Subject`, so it can be piped | Not an Observable; use the interop helpers |
| Cleanup | Manual for programmatic subscribers | Automatic on component destroy |
| Template syntax | `(x)="..."` | `(x)="..."`, unchanged |
Because the template syntax does not change, migrating does not affect parents. The Angular CLI has a schematic that rewrites declarations for you:
ng generate @angular/core:signal-queries-migration --help
ng generate @angular/core:output-migrationAfter running it, search for any remaining .pipe( or .next( calls on former emitters. The schematic skips those because they need the interop helpers instead.
Exercise
A ColorPickerComponent exposes change = output<string>() and contains a native <select>. The parent writes (change)="setColor($event)" and sometimes gets a DOM Event instead of a color string. Explain the cause and give the fix.
Show answer
The native change event from the <select> bubbles up to the <app-color-picker> host element. The parent's (change) binding listens there too, so it receives both the DOM event and the output's string. Rename the output to something that does not collide with a DOM event name, such as colorChange = output<string>(), and bind (colorChange)="setColor($event)".
Exercise
A child component starts a 5-second setTimeout that calls this.done.emit(). Users who navigate away within 5 seconds see error NG0953 in the console. Why does it happen, and how would you fix it?
Show answer
The component is destroyed before the timer fires, and emitting on an output of a destroyed component is an error. Store the timer handle and clear it on destroy, for example const id = setTimeout(...); inject(DestroyRef).onDestroy(() => clearTimeout(id));, with inject called in an injection context such as the constructor. With RxJS, use timer(5000).pipe(takeUntilDestroyed()) instead.
Exercise
Why does outputFromObservable() return an output without an emit() method, and how does a parent's template binding differ from binding to a normal output()?
Show answer
The source Observable is the only producer of events, so a manual emit() would add a second, competing source. The parent's binding is the same in both cases, (search)="run($event)". The parent cannot tell how the child produces its events.