Im working in a menu where the current section is gonna be select it on scroll, but when i try to get the offsetTop of the elements i get alway 0 for some reason, on the parentElement a get value for offsetTop but in this case does not work for me using the offsetTop of the parentElement because i have many childElements inside with different offsetTop.
Template
<div nxCol="12,12,8" *ngIf="selectedPlan && selectedPlan?.id != quotePlan.id && !loading"> <!-- Limits --> <h5 class="nx-margin-y-0" translate [id]="LIMITS_AND_PRICING_SECTION_ID" #limitPricing> page.service-detail.available-plan.menu.limit-pricing </h5> <mat-list class="mat-list-padding-none"> <mat-list-item><strong translate>global.label.limits</strong></mat-list-item> <mat-divider></mat-divider> <mp-service-plan-limit-display [limits]="selectedPlan?.limits"></mp-service-plan-limit-display> </mat-list> <mat-list class="nx-margin-top-m mat-list-padding-none"> <mat-list-item><strong translate>page.service-detail.pricing</strong></mat-list-item> <mat-divider></mat-divider> <mp-service-plan-price-display [prices]="selectedPlan?.prices" [planId]="selectedPlan?.id" [availablePlans]="true" ></mp-service-plan-price-display> </mat-list> <!-- /Limits --> <!-- Documentation --> <ng-container *ngIf="planSpecDocuments.length > 0"> <h5 class="nx-margin-top-3xl nx-margin-bottom-2xs" translate [id]="DOCUMENTATION_SECTION_ID" #documentation> page.service-detail.available-plan.menu.documentation </h5> <p class="nx-margin-0">Details how to embed the Service into your application.</p> <mat-list class="mat-list-padding-none mat-file-list"> <ng-container *ngFor="let specDocument of planSpecDocuments"> <mat-list-item> <ng-container *ngIf="(partnerId$ | async)?.length && !isPreview; else documentSpecDisabledTpl"> <a [href]="specDocument.specDocumentUrl | async" [download]="specDocument.name" class="file-links file-link-active"> <span class="icon-document mpt-icon"></span>{{ specDocument.name }} </a> </ng-container> <ng-template #documentSpecDisabledTpl> <span class="file-links"> <span class="icon-document mpt-icon"></span> {{ specDocument.name }} </span> </ng-template> </mat-list-item> </ng-container> </mat-list> </ng-container> <!-- /Documentation --> </div>
Component
@ViewChild('limitPricing') limitPricing!: ElementRef; @ViewChild('documentation') documentation!: ElementRef; @ViewChild('swaggerSpec') swaggerSpec!: ElementRef; timer(500).subscribe(() => { console.dir(this.limitPricing?.nativeElement); this.limitPricingOffset = this.limitPricing?.nativeElement.offsetTop - 100; // offsetTop here is always zero this.documentationOffset = this.documentation?.nativeElement.offsetTop - 100; this.swaggerSpecOffset = this.swaggerSpec?.nativeElement.offsetTop - 100; });
Advertisement
Answer
Declare the element in the constructor, as private _element: ElementRef) { ...}
this._element.nativeElement.getBoundingClientRect().top