Search code examples
angularangular8angular9angular-lifecycle-hooks

Angular 9 incorrect element height returned on ngAfterViewInit life hook


I am trying to get the height of header, on ngAfterViewInit life hook. Chrome says height is 172px(which is correct), but my code says height is 142px(sometime 140px).

Headercomponent.ts

import { Component, ElementRef, ViewChild, AfterViewInit} from '@angular/core';
@Component({
selector: 'app-header',
templateUrl: './header.component.html',
styleUrls: ['./header.component.css']
})
export class HeaderComponent implements AfterViewInit{

@ViewChild('headerIdentifier', {read: ElementRef, static:true}) elementView: ElementRef;
contentHeight: number;

ngAfterViewInit(): void {
   this.contentHeight = this.elementView.nativeElement.offsetHeight;
   console.log(this.contentHeight)
 }
}

appcomponent.html

<div class="main_wapper">
<app-header></app-header>
<app-baner></app-baner>
<section class="contentPart defineFloat">
<router-outlet></router-outlet>
</section>
<app-footer></app-footer>
</div>

There is no code in appcomponent.ts. Just plain component class.


Solution

  • So, after going through alot of research on angular articles. I have to come up with a hack for now.

      setTimeout(() => { this.contentHeight = this.elementView.nativeElement.offsetHeight;
      console.log(this.contentHeight) }, 1000 )
    

    I waited for 1 second on ngAfterViewInit & it worked like a charm.