0

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
  }
}
Wonjun Kim
  • 26
  • 4

1 Answers1

0

Use this -

ngAfterViewInit() {
    this.scrollTop = this.divArea.nativeElement.offsetHeight; // result: error
  }
  • You Local variable (#divArea) will be available to use within the ngAfterViewInit hook of angular.

  • Also @View Child should be @ViewChild without any space between.

  • <div #divarea"> should be <div #divarea>

Working Example

Pardeep Jain
  • 84,110
  • 37
  • 165
  • 215