Sub topic 7
Emitting events with outputs
What you need first
This chapter assumes you can already write a standalone attribute directive with @Directive, apply it through a component's imports array, and use host listeners and signal inputs. It also assumes you know event binding syntax such as (click)="save()". The examples use the signal-based output() function from @angular/core, available in current Angular versions.
Why a directive needs outputs
So far the directives in this tutorial have changed their host element and kept the result to themselves. Sometimes a directive detects something the surrounding component cares about, and it needs a way to report it. Examples include:
- a click that landed outside an element
- a press held for half a second
- a key combination
- a drag that crossed a threshold
An output is the channel for that. The directive emits a value, and the component that uses the directive listens with ordinary event binding syntax.
Outputs keep responsibilities separate. The directive knows how to detect the interaction. The parent component decides what to do about it, such as closing a menu, deleting an item, or logging. The directive never needs a reference to the parent.
Declaring an output with output()
Create an output by assigning the result of output<T>() to a class field. T is the type of the payload passed to listeners. Call .emit(value) to send an event.
This directive reports clicks that land outside its host element. It listens on document through the host metadata, so Angular adds the listener when the directive is created and removes it when the directive is destroyed.
import { Directive, ElementRef, inject, output } from '@angular/core';
@Directive({
selector: '[appClickOutside]',
host: {
'(document:click)': 'onDocumentClick($event)',
},
})
export class ClickOutsideDirective {
private el = inject<ElementRef<HTMLElement>>(ElementRef);
clickOutside = output<MouseEvent>();
onDocumentClick(event: MouseEvent) {
if (!this.el.nativeElement.contains(event.target as Node)) {
this.clickOutside.emit(event);
}
}
}The parent binds to the output by its field name, in parentheses, exactly as it would bind to a native event:
import { Component, signal } from '@angular/core';
import { ClickOutsideDirective } from './click-outside.directive';
@Component({
selector: 'app-menu',
imports: [ClickOutsideDirective],
template: `
<button (click)="open.set(!open())">Menu</button>
@if (open()) {
<ul appClickOutside (clickOutside)="open.set(false)">
<li>Profile</li>
<li>Sign out</li>
</ul>
}
`,
})
export class MenuComponent {
open = signal(false);
}Two details are worth checking in this code:
- The output is initialized in a field initializer.
output()needs an injection context, so a field initializer or the constructor works. Calling it later, for example insidengOnInit, throws an error. - The listener name
clickOutsideis the field name. The selectorappClickOutsideand the output name are separate things. The selector decides which elements get the directive. The output name is what appears in parentheses.
How the event reaches the parent
The directive does not dispatch a DOM event. It calls emit(), and Angular passes the value to the handlers the parent registered in its template. Nothing bubbles up the DOM tree, and an ancestor component cannot listen unless the directive's element is in its own template.
Event payloads and $event
In a template listener, $event holds the value passed to emit(). The type parameter of output<T>() controls what $event is and how the compiler checks it.
import { Directive, output } from '@angular/core';
@Directive({
selector: '[appResizeWatch]',
host: { '(window:resize)': 'report()' },
})
export class ResizeWatchDirective {
resized = output<{ width: number; height: number }>();
report() {
this.resized.emit({ width: window.innerWidth, height: window.innerHeight });
}
}<div appResizeWatch (resized)="onResize($event)"></div>If the event carries no data, use output<void>() and call emit() with no argument. Choose a payload that is stable and useful to the parent. Passing the raw MouseEvent, as in the click-outside example, is reasonable when the parent might want coordinates or modifier keys. For a derived fact such as a size, an object with named fields is clearer than a bare tuple.
A directive that owns a timer
Outputs often pair with state that lives inside the directive. A long-press detector starts a timer on pointerdown and emits only if the pointer stays down for the full duration. This version also takes the duration as an input and clears its timer when the directive is destroyed.
import { DestroyRef, Directive, inject, input, output } from '@angular/core';
@Directive({
selector: '[appLongPress]',
host: {
'(pointerdown)': 'start()',
'(pointerup)': 'cancel()',
'(pointerleave)': 'cancel()',
},
})
export class LongPressDirective {
pressDuration = input(500);
longPress = output<void>();
private timer: ReturnType<typeof setTimeout> | undefined;
constructor() {
inject(DestroyRef).onDestroy(() => this.cancel());
}
start() {
this.cancel();
this.timer = setTimeout(() => {
this.timer = undefined;
this.longPress.emit();
}, this.pressDuration());
}
cancel() {
clearTimeout(this.timer);
this.timer = undefined;
}
}<button appLongPress [pressDuration]="800" (longPress)="confirmDelete()">
Hold to delete
</button>The DestroyRef callback matters here. If the element is removed while the timer is pending, the callback would otherwise run after destruction and call emit() on a destroyed directive.
Naming and aliasing
Give an output an alias when the public name should differ from the field name:
import { Directive, output } from '@angular/core';
@Directive({ selector: '[appDismissable]' })
export class DismissableDirective {
closed = output<void>({ alias: 'dismissed' });
}The template then uses (dismissed), while the class still refers to this.closed. Aliases are mainly useful for keeping a stable public API while you rename internals. They are also useful when composing with hostDirectives, which can expose outputs under new names.
Choose names with these rules:
- Do not reuse the name of a native DOM event such as
click,focus, orinput. A listener written as(click)on an element would then be ambiguous. Angular binds it to both the native event and your output. - Do not prefix output names with
on. Write(clickOutside), not(onClickOutside). Handler methods in the parent can use theonprefix. - Use a name that describes what happened, in the past or as a noun:
closed,resized,longPress.
Other ways to produce and consume outputs
output() returns an OutputEmitterRef. It has emit() for sending values and subscribe() for listening from code. The subscribe() method returns an object with unsubscribe(). Template listeners are cleaned up for you, but a manual subscription is your responsibility unless you tie it to the lifetime of something that is destroyed.
When the event source is already an RxJS observable, outputFromObservable() from @angular/core/rxjs-interop turns it into an output without a manual emit() call. Angular subscribes when something listens to the output and unsubscribes when the directive is destroyed.
import { DOCUMENT } from '@angular/common';
import { Directive, inject } from '@angular/core';
import { outputFromObservable } from '@angular/core/rxjs-interop';
import { filter, fromEvent } from 'rxjs';
@Directive({ selector: '[appEscape]' })
export class EscapeDirective {
private doc = inject(DOCUMENT);
escaped = outputFromObservable(
fromEvent<KeyboardEvent>(this.doc, 'keydown').pipe(
filter((event) => event.key === 'Escape'),
),
);
}Field order matters here. doc must be declared before escaped, because field initializers run in order. The companion function outputToObservable() goes the other way and wraps an existing output as an observable.
Older code uses the @Output() decorator with EventEmitter. It still works, and you will meet it in existing code bases. For new directives prefer output(). It has a smaller API (no next, pipe, or other Subject methods that you should not call on an output) and it is checked consistently with signal inputs.
| Approach | Use it when | Notes |
|---|---|---|
| `output<T>()` | You detect the condition in your own code | Call `emit()` yourself |
| `outputFromObservable()` | The source is already an observable | No manual `emit()`, lifecycle handled for you |
| `@Output()` with `EventEmitter` | You maintain older code | Avoid in new directives |
Edge cases and pitfalls
- Emitting after destruction. Calling
emit()on an output whose directive has been destroyed throws an error. Timers, promises, and manual subscriptions are the usual causes. Cancel them in aDestroyRefcallback, as the long-press directive does. - The opening click counts as outside. In the menu example, the click that opens the list can reach
documentafter the list has been rendered. The new directive then sees a click outside its host and closes the list immediately. A reliable fix is to check in the parent handler whetherevent.targetis inside the trigger button, and to ignore the event if it is. - Cost of document listeners. Each
(document:click)listener runs for every click on the page, and each run can trigger change detection. A page with hundreds of instances pays for all of them. Create the directive only on elements that are currently open, as the@ifin the menu does. - Output vs. input confusion. Data flows into a directive through inputs and out through outputs. The parent should not read the directive's fields to learn about events. If the parent needs the directive instance itself, that is the job of
exportAs, covered in the next chapter. - Mutating the payload. If the payload is an object or a DOM event, every listener sees the same instance. Treat it as read-only.
Summary of the working model
A directive declares an output with output<T>() in a field initializer. It calls emit() when its detection logic fires. The parent binds with (outputName)="handler($event)", and $event is the emitted value. Names should describe the event, avoid native event names, and avoid an on prefix. Anything the directive starts, such as timers or manual subscriptions, must be stopped when the directive is destroyed so it never emits afterward.
Exercise
A <div appClickOutside (clickOutside)="close()"> closes a panel, but the panel also closes when the user clicks a button inside it. The directive code is if (this.el.nativeElement.contains(event.target as Node)) { this.clickOutside.emit(event); }. What is wrong, and what is the fix?
Show answer
The condition is inverted. It emits when the click is inside the host. It should emit when contains() is false, so the check needs a negation: if (!this.el.nativeElement.contains(event.target as Node)) { this.clickOutside.emit(event); }.
Exercise
You write a directive with output<void>() and a setTimeout that calls emit() after 2 seconds. Users sometimes navigate away before the timer fires, and the console shows an error about an unexpected emit. What causes it, and how do you prevent it?
Show answer
The timer fires after the directive has been destroyed, and emitting on the output of a destroyed directive throws. Store the timer id and clear it in a callback registered with inject(DestroyRef).onDestroy(...), so the timer never fires after destruction.
Exercise
Write the field declaration for an output named closed that parents bind to as (dismissed), with no payload.
Show answer
closed = output<void>({ alias: 'dismissed' }); Parents then write (dismissed)="handler()", while the class keeps using this.closed.emit().