Sub topic 7
Emitting Events with Outputs
This chapter assumes you can write a standalone attribute directive, apply it through a component's imports array, and use event binding such as (click)="...". It builds on the earlier chapters about host listeners and inputs.
Why a directive needs an output
An input sends data from the template into the directive. An output sends a signal the other way: the directive tells the parent template that something happened, and the parent decides what to do about it.
The directive should detect the situation, such as "the user clicked somewhere else", and the parent component should own the response, such as closing a panel or saving a draft. The directive stays reusable because it does not know what the response is.
Declaring an output with output()
Use the output() function and call it in a field initializer. It returns an OutputEmitterRef<T>. You send a value to listeners by calling emit().
The directive below emits when a click lands outside its host element.
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);
}
}
}Three details matter here:
output<MouseEvent>()sets the type of the value thatemit()accepts and that$eventhas in the template.- The
document:clickentry inhostmakes Angular add the listener when the directive is created and remove it when the directive is destroyed. You do not write cleanup code. contains()returnstruefor the host itself and for all of its descendants. A plain===comparison would treat a click on a child element as "outside".
Listening in a template
The output name becomes an event name in the template. Bind to it with parentheses, exactly as you would bind to a DOM event.
import { Component, signal } from '@angular/core';
import { ClickOutsideDirective } from './click-outside.directive';
@Component({
selector: 'app-outside-demo',
imports: [ClickOutsideDirective],
template: `
<div appClickOutside (clickOutside)="onOutside($event)">
Click inside this box, then outside it.
</div>
<p>{{ message() }}</p>
`,
})
export class OutsideDemoComponent {
message = signal('Waiting for a click.');
onOutside(event: MouseEvent) {
this.message.set(`Clicked outside at x=${event.clientX}`);
}
}$event holds whatever the directive passed to emit(). If the output carries no data, declare it as output<void>() and call emit() with no argument.
Naming and aliases
Name an output after what happened, in the past tense or as a noun phrase: clickOutside, dismissed, colorChange. Two rules apply:
- Do not use a native DOM event name such as
clickorinput. The parent's(click)binding would then fire for both the native event and your emission, which is hard to debug. - Do not prefix names with
on. Angular's style guide recommends against it.
If you need a template name that differs from the property name, pass an alias: output<MouseEvent>({ alias: 'outside' }). The parent then writes (outside)="...".
Common errors
- Calling
output()outside an injection context. It works as a field initializer or in the constructor. Calling it inside a method throws a runtime error. - Forgetting the directive in
imports. IfClickOutsideDirectiveis missing, Angular does not treat(clickOutside)as a directive output. It treats it as a plain DOM event listener, so the handler never runs. - Subscribing manually and never unsubscribing. In a template this is automatic. If you use
outputToObservable()orsubscribe()in code, clean up the subscription yourself.
Exercise
Why does ClickOutsideDirective use this.el.nativeElement.contains(event.target as Node) instead of event.target === this.el.nativeElement?
Show answer
A click on a child of the host has the child as its target, so the equality check would report it as outside. contains() is true for the host and all its descendants, so only clicks outside the whole element emit the output.
Exercise
Change the directive so that it also emits when the user presses the Escape key, using a second output called escaped of type void. Which host entry and which emit call do you add?
Show answer
Add '(document:keydown.escape)': 'escaped.emit()' to the host object, and declare escaped = output<void>(); in the class. The parent listens with (escaped)="...".