import { ElementRef, Inject, Injectable, } from '@angular/core'; @Injectable() export class DomElementLocationService { constructor( @Inject('window') private _window: Window, ) {} public getCenterPointOfElement( elementRef: ElementRef, ) { const boundingRect = elementRef.nativeElement .getBoundingClientRect(); return boundingRect.top + boundingRect.height / 2; } public getMostCentralElement( elementRefs: ElementRef[], ) { const centerPoint = this._window .innerHeight / 2; let mostCentral = elementRefs[0]; let mostCentralIndex = 0; elementRefs.forEach((prodViewEl, index) => { const newElDistance = this.getCenterPointOfElement(prodViewEl) - centerPoint; const oldElDistance = this.getCenterPointOfElement(mostCentral) - centerPoint; if (Math.abs(newElDistance) < Math.abs(oldElDistance)) { mostCentral = prodViewEl; mostCentralIndex = index; } }); return { mostCentral, mostCentralIndex, }; } }