javascriptangulardomcontentloaded

Reloading DOMContent


I understand angular is one page application with multiple components and use route to interact between pages.

We have an angular app like that. One of the requirements is that on a specific component we need to add an eventListener to DomContentLoaded event.

Since the index.html page has been loaded (hence DomContentLoaded event has been fired) way before, we have a problem.

I cannot find a way to re-trigger the DomContentLoaded event.


Solution

  • The DomContentLoaded event fired before the first component was created. You can however use the ngAfterViewInit() method. ngAfterViewInit() is a callback method that is invoked immediately after Angular has completed initialization of a component's view. It is invoked only once when the view is instantiated.

    class YourComponent {
        ngAfterViewInit() {
            // Your code here
        }
    }
    

    If you really need to catch the DomContentLoaded event anyway, do it in the main.ts file.