1 | import { EventEmitter, Directive, ElementRef, Renderer2, ViewContainerRef, Output, ContentChild, TemplateRef, NgModule } from '@angular/core';
|
2 | import { CommonModule } from '@angular/common';
|
3 |
|
4 | class DeferredLoader {
|
5 | constructor(el, renderer, viewContainer) {
|
6 | this.el = el;
|
7 | this.renderer = renderer;
|
8 | this.viewContainer = viewContainer;
|
9 | this.onLoad = new EventEmitter();
|
10 | }
|
11 | ngAfterViewInit() {
|
12 | if (this.shouldLoad()) {
|
13 | this.load();
|
14 | }
|
15 | if (!this.isLoaded()) {
|
16 | this.documentScrollListener = this.renderer.listen('window', 'scroll', () => {
|
17 | if (this.shouldLoad()) {
|
18 | this.load();
|
19 | this.documentScrollListener();
|
20 | this.documentScrollListener = null;
|
21 | }
|
22 | });
|
23 | }
|
24 | }
|
25 | shouldLoad() {
|
26 | if (this.isLoaded()) {
|
27 | return false;
|
28 | }
|
29 | else {
|
30 | let rect = this.el.nativeElement.getBoundingClientRect();
|
31 | let docElement = document.documentElement;
|
32 | let winHeight = docElement.clientHeight;
|
33 | return (winHeight >= rect.top);
|
34 | }
|
35 | }
|
36 | load() {
|
37 | this.view = this.viewContainer.createEmbeddedView(this.template);
|
38 | this.onLoad.emit();
|
39 | }
|
40 | isLoaded() {
|
41 | return this.view != null;
|
42 | }
|
43 | ngOnDestroy() {
|
44 | this.view = null;
|
45 | if (this.documentScrollListener) {
|
46 | this.documentScrollListener();
|
47 | }
|
48 | }
|
49 | }
|
50 | DeferredLoader.decorators = [
|
51 | { type: Directive, args: [{
|
52 | selector: '[pDefer]'
|
53 | },] }
|
54 | ];
|
55 | DeferredLoader.ctorParameters = () => [
|
56 | { type: ElementRef },
|
57 | { type: Renderer2 },
|
58 | { type: ViewContainerRef }
|
59 | ];
|
60 | DeferredLoader.propDecorators = {
|
61 | onLoad: [{ type: Output }],
|
62 | template: [{ type: ContentChild, args: [TemplateRef,] }]
|
63 | };
|
64 | class DeferModule {
|
65 | }
|
66 | DeferModule.decorators = [
|
67 | { type: NgModule, args: [{
|
68 | imports: [CommonModule],
|
69 | exports: [DeferredLoader],
|
70 | declarations: [DeferredLoader]
|
71 | },] }
|
72 | ];
|
73 |
|
74 |
|
75 |
|
76 |
|
77 |
|
78 | export { DeferModule, DeferredLoader };
|
79 |
|