Last active
April 18, 2018 21:15
-
-
Save allenhwkim/4f87ee848043e88a92d61124b85b369e to your computer and use it in GitHub Desktop.
Simple Lazy Loading With Angular
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| @Component({ | |
| selector: 'ngui-in-view', | |
| template: ` | |
| <ng-container *ngIf="inView" [ngTemplateOutlet]="template"> | |
| </ng-container> | |
| `, | |
| styles: [':host {display: block;}'] | |
| }) | |
| export class NguiInViewComponent implements OnInit, OnDestroy { | |
| observer: IntersectionObserver; | |
| inView: boolean = false; | |
| once50PctVisible: boolean = false; | |
| @ContentChild(TemplateRef) template: TemplateRef<any>; | |
| @Input() options: any = { threshold: [.1, .2, .3, .4, .5, .6, .7, .8] }; | |
| @Output('inView') inView$: EventEmitter<any> = new EventEmitter(); | |
| @Output('notInView') notInView$: EventEmitter<any> = new EventEmitter(); | |
| constructor( | |
| public element: ElementRef, | |
| public renderer: Renderer2, | |
| @Inject(PLATFORM_ID) private platformId: any) { } | |
| ngOnInit(): void { | |
| if (isPlatformBrowser(this.platformId)) { | |
| this.observer = new IntersectionObserver(this.handleIntersect.bind(this), this.options); | |
| this.observer.observe(this.element.nativeElement); | |
| } | |
| } | |
| ngOnDestroy(): void { | |
| this.observer.disconnect(); | |
| } | |
| handleIntersect(entries, observer): void { | |
| entries.forEach((entry: IntersectionObserverEntry) => { | |
| if (entry.isIntersecting) { | |
| this.inView = true; | |
| this.inView$.emit(entry); | |
| } else { | |
| this.notInView$.emit(entry); | |
| } | |
| }); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment