2

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

1 Answer 1

4

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" });
 }
2
  • But what if I have 100 "viewChilds" per page? Then its pretty hard to define them in my .ts
    – Timo
    Nov 26, 2022 at 18:21
  • I think your code-snippet is not comprehensive enough to get a concise response of any user here. You definitely need to give more context. I recommend to add 1.) all the relevant code of the ts-file (e.g. users should see what this.jumpedToMessage or this.jumpMessage is and how you get the value for these fields). 2.) The HTML part might be important as well.
    – kellermat
    Nov 26, 2022 at 18:30

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.