Search code examples
jqueryangulartypescriptangular-lifecycle-hooks

jquery not finding items when routing in Angular


I have the following code inside my angular component that is run inside ngOnInit():

animateMobileSkillBar() : void {
    console.log("Animation skillbar out");
    $( document ).ready(function() {
      console.log("Animation skillbar inside document ready");
      $(".skillbars").each(function() {
        console.log("Animation skillbar for each skillbar");
        // The stuff I need to do...
      }
    }
}

I added the $(document).ready because it didn't work before. Now it works on page load. But when I do routing it does not. I know the script is running and I get printed "Animation skillbar inside document ready". So for some reason, the problem is $(".skillbars").each().

Why is this not working? I feel as if the skillbars are not ready but that was the goal of document.ready right?


Solution

  • You can move your implementation into ngAfterViewInit(). where the view will be initialized with all bindings. For more information look the link https://angular.io/api/core/AfterViewInit.

    You do not need to do this document.ready.