Skip to main content

Events of Component

· One min read

Open in Notion

Outside Click

import { Directive, Input, Output, EventEmitter, ElementRef, HostListener } from '@angular/core';

@Directive({
selector: '[clickOutside]',
})
export class ClickOutsideDirective {

@Output() clickOutside = new EventEmitter<void>();

constructor(private elementRef: ElementRef) { }

@HostListener('document:click', ['$event.target'])
public onClick(target) {
const clickedInside = this.elementRef.nativeElement.contains(target);
if (!clickedInside) {
this.clickOutside.emit();
}
}
}
<div (clickOutside)="someHandler()"></div>

Keydown of Component

@HostListener('document: keydown', ['$event'])
public onEnter(event: KeyboardEvent): void {
if (this.elementRef.nativeElement.contains(event.target)) {
if (event.code === 'Enter') {
// TODO:
}
}
}

‼️Tips

If the element contains *ngIf, this.overlay.nativeElement.contains(event.target); always return false. Because of the angular directive *ngIf

<div #overlay>
<div *ngIf="show" class="item">
Click here
</div>
</div>
@ViewChild('overlay', { static: false }) overlay: ElementRef;

//...
this.overlay.nativeElement.contains(event.target); // always return false

How to solve it?

You can check the event.target

Object.keys(event.target.classList).includes('item');

Or use [hidden] instead.

<div [hidden]="!show" class="item">
Click here
</div>