Skip to content
Advertisement

How to make sure ngAfterViewInit runs after a certain HTML element is rendered?

In HTML, there is a <a> that redirects to another component, and after that scrolls to a certain anchor.

In the target component, I have the following code

JavaScript

However, I found that document.getElementById(fragment); is always null, because this element is displayed conditionally using ngIf = booleanVariable, and when this ngAfterViewInit life cycle hook runs, this booleanVariable is not calculated yet.

I am wondering how to make sure ngAfterViewInit runs after booleanVariable is calculated and therefore this element is rendered?

I tried to use setTime but it seems hacky…

Thanks in advance!

Advertisement

Answer

Thanks for the answers but they don’t work properly I am afraid… (Perhaps I tried them in a wrong way.)

I managed to solve this problem using

JavaScript

The method will run after this ViewChild is rendered.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement