I'm building directive which should add class when element entered viewport and will also trigger custom event. I found 2 approaches to trigger the event - EventEmitter
and dispatchEvent()
, both works fine. Which should be used in this case and why? (Any other advices on the code appreciated)
import { EventEmitter, Directive, ElementRef, Renderer2, OnInit } from '@angular/core';
import { HostListener } from "@angular/core";
import { Component, Input, Output, Inject, PLATFORM_ID, ViewChild, ViewEncapsulation } from "@angular/core";
import { isPlatformBrowser, isPlatformServer } from '@angular/common';
import { AfterViewInit } from '@angular/core/src/metadata/lifecycle_hooks';
@Directive({
selector: '[animateOnVisible]',
})
export class AnimateOnVisibleDirective implements AfterViewInit {
@Input() animateOnVisible: string = "fadeInUp";
@Output() enteredViewport: EventEmitter<string> = new EventEmitter();
public isBrowser: boolean;
private enableListener: boolean = true;
constructor(private renderer: Renderer2, private hostElement: ElementRef, @Inject(PLATFORM_ID) private platformId: any) {
this.isBrowser = isPlatformBrowser(platformId);
}
@HostListener("window:scroll", [])
onWindowScroll() {
this.checkScrollPosition();
}
ngAfterViewInit() {
this.checkScrollPosition();
}
private checkScrollPosition() {
if (this.isBrowser && this.enableListener && window.scrollY + window.innerHeight / 2 >= this.hostElement.nativeElement.offsetTop) {
this.renderer.addClass(this.hostElement.nativeElement, this.animateOnVisible);
this.enableListener = false;
//triggering custom event
this.enteredViewport.emit("");
//OR
this.hostElement.nativeElement.dispatchEvent(new Event('enteredViewport', { bubbles: true }));
}
}
}
<div class="animated" [animateOnVisible]="'test'" (enteredViewport)="test()">
EventEmitter
is used for @Output()
s that can be used for Angular event binding
<my-component (myEvent)="doSomething()"
dispatchEvent()
fires a DOM event, that also can be bound to like shown for the Angular @Output()
event, but can also bubble up the DOM tree.
The former is specific to Angular and for the intented use cases more efficient, the later behaves like other DOM events and can also be listened to by non-Angular code, but might be less efficient.