Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 do actions after dom has finished rendering

I have a large ngx-bootstrap accordion on the page. When i open some of the lower accordions i want it to scroll the page so that the opened accorion starts at the top of the window. I achieved the scrolling part with scrollIntoView, but now the issue is to execute it at the right time. im currently doing it in the ngAfterViewChecked, but the viewChecked is fired multiple times (mousemove, mouseenter, etc...). Is there a way to fire a piece of code only after the DOM has finished rendering separately from the angular2+ changeDetection?

SOLUTION

This is the solution that started working.

constructor(elementRef: ElementRef) {
    this.elementRef = elementRef
  }

getData(){
   this.getService().then(result => {
      #do stuff with result
      setTimeout(() => this.scrollToBegin());
    }).catch((err: any) => {
    });
}

scrollToBegin(): any{
      this.elementRef.nativeElement.scrollIntoView();
    }
like image 814
Marko Taht Avatar asked Jan 27 '26 10:01

Marko Taht


1 Answers

AFAIK you just have ngAfterViewChecked and ngAfterViewInit for detecting dom updates.

In my experience, sometimes you need to write the code for dom changes inside a settimeout to schedule a macrotask (asynchronous update) for that so that your code will run in the next cycle of change detection (which is exactly what you need). For more details see this article

Place your could inside a settimeout in the end of your block code (and remove it from ngAfterViewChecked). Some examples:

setTimeout(() => htmlInputElement.focus()); // focus an input
setTimeout(() => htmlElement.scrollIntoView()); // scroll into view
like image 95
Vahid Avatar answered Jan 29 '26 00:01

Vahid



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!