ngAfterViewInit生命挂钩上返回的Angular 9元素高度不正确



我正在ngAfterViewInit生命挂钩上尝试获取标头的高度。Chrome说高度是172px(这是正确的(,但我的代码说高度是142px(有时是140px(。

收割台组件.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>

appcomponent.ts中没有代码。只有普通的组件类。

所以,在经历了大量关于角度文章的研究之后。我现在必须想出一个破解方法。

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

我在ngAfterViewInit&它就像一个符咒。

最新更新