why Jquery not load when change route in angular 7?

Viewed 2395

I have a problem when navigate between routes with angular 7, for example... i have this code in my app-component.html

<app-navbar *ngIf="currentUser"></app-navbar>
<router-outlet></router-outlet>
<app-footer *ngIf="currentUser"></app-footer>

Everything in the page works, the <router-outlet></router-outlet> have the main component for the page, this component have inside another component, the <app-leftmenu></app-leftmenu> this is the sidebar; originally this was a html-bootstrap 3 template that i segmented for use in angular cli.

Ok the reason for this question is that the SIDEBAR uses jquery for the basic actions like collapse and expand using the next code:

//
// Sidebar categories
//

// Hide if collapsed by default
$('.category-collapsed').children('.category-content').hide();


// Rotate icon if collapsed by default
$('.category-collapsed').find('[data-action=collapse]').addClass('rotate-180');


// Collapse on click
$('.category-title [data-action=collapse]').click(function (e) {
    e.preventDefault();
    var $categoryCollapse = $(this).parent().parent().parent().nextAll();
    $(this).parents('.category-title').toggleClass('category-collapsed');
    $(this).toggleClass('rotate-180');

    containerHeight(); // adjust page height

    $categoryCollapse.slideToggle(150);
});

But not work in angular, only when i reload once time the component if i navigate to other route the sidebar ignore the jquery, but refreshing the page works... how i resolve this... with no refreshing? Thanks for the help!

2 Answers

Presumably because at the time your jQuery code is executed $('.category-collapsed'), there is no such element.

Try jQuery.on(), which allows for later binding: https://api.jquery.com/on/

So this

$('.category-title [data-action=collapse]').click(fn)

becomes (untested)

$(document).on('click', '.category-title [data-action=collapse]', fn)

I would strongly suggest using Angular-Bootstrap instead of a vanilla javascript/jquery solution.

https://ng-bootstrap.github.io/#/home

This library provides a variety of standard UI components - tabbed interfaces, dropdowns, accordion menus etc. all as native Angular components with full TypeScript support.

Related