我正在尝试获取标题的高度,在ngAfterViewInit生活挂钩。Chrome说高度是172px(这是正确的),但我的代码说高度是142px(有时是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>
appcomponent.ts中没有代码。只是简单的组件类。
发布于 2020-05-22 01:06:54
所以,在对angular文章进行了大量的研究之后。我现在得想个办法了。
setTimeout(() => { this.contentHeight = this.elementView.nativeElement.offsetHeight;
console.log(this.contentHeight) }, 1000 )
我在ngAfterViewInit上等了1秒钟&它就像一个护身符。
https://stackoverflow.com/questions/61709977
复制相似问题