specgen
Version:
Angular - Jasmine Unit Test Spec file Generator
65 lines (57 loc) • 1.67 kB
text/typescript
import {
Directive,
ElementRef,
EventEmitter,
Inject,
Input,
OnDestroy,
OnInit,
Output,
PLATFORM_ID,
Renderer2,
ViewChild
} from '@angular/core';
import { isPlatformBrowser } from '@angular/common';
export class MyDirective implements OnInit, OnDestroy {
observer: IntersectionObserver;
/** IntersectionObserver options */
options: any = {};
/** Event that will be fired when in viewport */
nguiInview: EventEmitter<any> = new EventEmitter();
/** Event that will be fired when out of viewport */
nguiOutview: EventEmitter<any> = new EventEmitter();
constructor(
public element: ElementRef,
public renderer: Renderer2,
private platformId: any) {
}
/** Starts IntersectionObserver */
ngOnInit(): void {
if (isPlatformBrowser(this.platformId)) {
this.observer = new IntersectionObserver(this.handleIntersect.bind(this), this.options);
this.observer.observe(this.element.nativeElement);
}
}
/** Stops IntersectionObserver */
ngOnDestroy(): void {
if (isPlatformBrowser(this.platformId)) {
this.observer && this.observer.disconnect();
}
}
/**
* Fires (nguiInview) event when this element is in viewport
* and fires (nguiOutview) event when this element is not in viewport
*/
handleIntersect(entries, observer): void {
entries.forEach((entry: IntersectionObserverEntry) => {
if (entry['isIntersecting']) {
this.nguiInview.emit(entry);
} else {
this.nguiOutview.emit(entry);
}
});
}
}