An Angular directive to detect when an element is within the browser viewport.
Run npm run build to build the library. The build artifacts will be stored in the dist/angular-in-viewport directory.
Run npm run start to build the library and run the demo.
Run npm run watch to run the in watch mode the library and demo.
npm i @talentia/angular-in-viewportDirective selector: ngxInViewPort
<div ngxInViewPort (inViewport)="showElement=true">
<ng-container *ngIf="showElement"> <div>Hello World!</div> </ng-container>
</div>If
entry.intersectionRatio >= 0.5==>Inside Viewport>
Ifentry.intersectionRatio < 0.5==>Outside Viewport
lazy loading images example
<div *ngFor="let image of images" ngxInViewPort [oneTime]="true" (inViewport)="show($event, image)">
<ng-container *ngIf="image.show"> <img src="{{ image.url }}" /> </ng-container>
</div> show(event: Partial<IntersectionObserverEntry>, image: ImageItem) {
if (event.intersectionRatio >= 0.5) {
image.show = true;
}
}- Trigger only one time :
[oneTime]="true"use case: image loading. - Server-Side Rendering : By default, loads the elements on the server.
If you do not want to pre-render the elements in server, you can set
preRender to false. i.e.,[preRender]="false"`
You can use
InViewportServiceitself in any Component
import { ElementRef, OnDestroy, OnInit } from '@angular/core';
import { untilDestroy, InViewportService } from '@talentia/angular-in-viewport';
export class ViewportDemoComponent implements OnInit, OnDestroy {
public constructor(private element: ElementRef, private viewportService: InViewportService) {}
public ngOnInit(): void {
this.viewportService
.observe(this.element.nativeElement)
.pipe(untilDestroy(this))
.subscribe((entry: IntersectionObserverEntry) => {
if (entry.isIntersecting) {
this.show();
} else {
this.hide();
}
});
}
ngOnDestroy() {}
private show(): void {
// => Animation
}
private hide(): void {
// <= Animation
}
}This project was generated with Angular CLI version 18.2.14.
To get more help on the Angular CLI use ng help or go check out the Angular CLI Overview and Command Reference page.