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?


This is the solution that started working.

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

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

scrollToBegin(): any{


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

Answered By – Vahid

Answer Checked By – Gilberto Lyons (AngularFixing Admin)

Leave a Reply

Your email address will not be published.