I want to get the height of divArea
and store it in the scrollTop
variable.
However, When I initialize scrollTop
to this.divArea.nativeElement.offsetHeight
in onInit function, an error occurred.
The error is that divArea
is null.
One workaround is to use setTimeout().
But I do not want to use settimeout()
.
How to solve this problem?
html
<div #divarea>
<p>Hello1</p>
<p>Hello1</p>
<p>Hello1</p>
<p>Hello1</p>
</div>
<div [style.top.px]="scrollTop">
...
</div>
ts
export class test implements OnInit {
public scrollTop: number;
@ViewChild('divarea') private divArea: ElementRef;
public ngOnInit() {
this.scrollTop = this.divArea.nativeElement.offsetHeight; // result: error
}
}