Angular app, cannot get getBoundingClientRect of any element

155 Views Asked by At

I have an angular project which is half way through development, I am using SSR with universal (mentioning just in case it matters although it doest not run in dev mode), bootstap and ng-bootstrap on Angular 15. I noticed some odd behaviour with ng-bootstrap dropdowns not being positioned correctly but i assumed it was something simple but now i am noticing whenever i am trying to get the getBoundingClientRect of any element its always coming back as 0 for top, left, bottom, right.

Im really not sure what else to say, its confusing. has anyone else come across this issue ?

  import { AfterViewInit, Component, ElementRef, OnDestroy, OnInit, ViewChild } from '@angular/core';

  @Component({
    selector: 'app-xxx',
    templateUrl: './xxx.component.html',
    styleUrls: ['./xxx.component.scss']
  })
  export class XXXComponent implements OnDestroy, OnInit, AfterViewInit {

    @ViewChild('demoE', { static: false }) demoE!: ElementRef;
    
    constructor( ) {}
    
    ngAfterViewInit(): void {
      setTimeout(() => {
        const element: HTMLElement = this.demoE.nativeElement;
        const rect = element.getBoundingClientRect();
        alert(JSON.stringify(rect))
        const distanceFromTop = rect.top;
        const distanceFromLeft = rect.left;
        console.log('Distance from top:', distanceFromTop);
        console.log('Distance from left:', distanceFromLeft);      
      }, 2000);

    }
      
  }

I have this html buried at the bottom of the page so it should be returning some bounds, ive also tried in multiple other components and cant get a bounds for anything at all

  <div #demoE class="row">
  <div class="col-12">
    Helo
  </div>
</div>  

when i alert(JSON.stringify(rect)) i get the following value `{"ngContext":13}

1

There are 1 best solutions below

0
Rahul Sahu On

In angular universal code is being executed on express server not is browser. And there are some properties which exists only on browser example,

  1. window and document
  2. getBoundingClientRect()
  3. offsetHeight, offsetWidth (all window measurement proper ties)
  4. sessionStorage
  5. localStorage etc.

But you can use a special document object by injecting into constructor.

@Inject(DOCUMENT) private document:Document,

Then you can also access special window object by using injected document,

this.window = this.document.defaultView;

It will allow you to create global variables, access DOM manipulation functions like getElementById

But browser specific properties will be still inaccessible which I added in bullet points