Search code examples
javascriptangulartypescriptscroll

Angular 14 - Scroll to div with specific id


I want to scoll to a div after my view has initialized the first time. My problem so far is that AfterViewInit leads to a problem, because its not fully rendered. (Fetched data from server, then render that..)

Code so far:

  scrollTo(): void {
    if (!this.jumpedToMessage && this.jumpMessage != "0") {
      const element = document.getElementById(this.jumpMessage);
      // @ts-ignore
      element.scrollIntoView({behavior: 'auto', block: 'center', inline: 'nearest'});
      this.jumpedToMessage = true
    }
  }

Error code in console:

my-component.ts:58 ERROR TypeError: Cannot read properties of null (reading 'scrollIntoView') at my-component.scrollTo (my-component.component.ts:76:15) at Object.next (my-component.component.ts:65:18) at ConsumerObserver.next (Subscriber.js:91:33) at SafeSubscriber._next (Subscriber.js:60:26) at SafeSubscriber.next (Subscriber.js:31:18) at map.js:7:24 at OperatorSubscriber._next (OperatorSubscriber.js:13:21) at OperatorSubscriber.next (Subscriber.js:31:18) at filter.js:6:128 at OperatorSubscriber._next (OperatorSubscriber.js:13:21)

Any ideas how to solve this?

Important: Initialize only once after the first rendering


Solution

  • Maybe you can try a different approach to achieve your goal, by using @ViewChild, which would be more Angular-like anyway.

    In your HTML:

    <p #scrollElement>Scroll here</p>
    

    Then in your TS-File:

     @ViewChild("scrollElement")
     scrollEl: ElementRef;
    
     ngAfterViewInit() {
        this.scrollEl.nativeElement.scrollIntoView({ behavior: "smooth", block: "start" });
     }