Angular 2 execute script after template render

Solution 1:

ngAfterViewInit() of AppComponent is a lifecycle callback Angular calls after the root component and its children have been rendered and it should fit for your purpose.

See also https://angular.io/guide/lifecycle-hooks

Solution 2:

Actually ngAfterViewInit() will initiate only once when the component initiate.

If you really want a event triggers after the HTML element renter on the screen then you can use ngAfterViewChecked()

Solution 3:

I have found that the best place is in NgAfterViewChecked(). I tried to execute code that would scroll to an ng-accordion panel when the page was loaded. I tried putting the code in NgAfterViewInit() but it did not work there (NPE). The problem was that the element had not been rendered yet. There is a problem with putting it in NgAfterViewChecked(). NgAfterViewChecked() is called several times as the page is rendered. Some calls are made before the element is rendered. This means a check for null may be required to guard the code from NPE. I am using Angular 8.