首页 > 解决方案 > 为什么在角度 7 中更改路线时 Jquery 不加载?

问题描述

例如,在使用角度 7 的路线之间导航时出现问题...我的 app-component.html 中有此代码

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

页面中的所有内容都有效,<router-outlet></router-outlet>有页面的主要组件,这个组件有另一个组件,<app-leftmenu></app-leftmenu>这是侧边栏;最初这是一个 html-bootstrap 3 模板,我对其进行分段以在 Angular cli 中使用。

好的,这个问题的原因是 SIDEBAR 使用 jquery 进行基本操作,例如使用下一个代码折叠和展开:

//
// 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);
});

但不能在角度工作,只有当我重新加载一次组件时,如果我导航到其他路线,侧边栏会忽略 jquery,但刷新页面有效......我如何解决这个问题......没有刷新?谢谢您的帮助!

标签: javascriptjqueryangularangular6angular7

解决方案


大概是因为在执行您的 jQuery 代码时$('.category-collapsed'),没有这样的元素。

Try jQuery.on(),它允许以后绑定:https ://api.jquery.com/on/

所以这

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

变成(未经测试)

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

推荐阅读