在Angular中导航时,第三方库无法正常工作

时间:2018-03-07 07:24:31

标签: angularjs angular2-routing

我添加了一些第三方库。(Bootstrap,Jquery和boot-strap-select(http://silviomoreto.github.io/bootstrap-select/))

当我浏览网页" boot-strap-select"不管用。 但是当我刷新页面时它会起作用。 但我很想知道如果没有刷新,bootstrap是如何工作的。

我使用npm安装了库,并在angular-cli.json

中定义
  "styles": [
    "styles.css",
    "../node_modules/bootstrap/dist/css/bootstrap.min.css",
    "../node_modules/bootstrap-select/dist/css/bootstrap-select.css"
  ],
  "scripts": [
    "../node_modules/jquery/dist/jquery.min.js",
    "../node_modules/bootstrap/dist/js/bootstrap.min.js",
    "../node_modules/bootstrap-select/dist/js/bootstrap-select.js"
  ]

我尝试在DOM中重新创建脚本元素,但它刷新页面(下面提到的链接)。

Load scripts through all components in Angular 2

https://github.com/angular/angular-cli/issues/4619

我想在导航时不加载页面而加载第三方库。

源代码: RepoLink

1 个答案:

答案 0 :(得分:0)

你需要了解的是,JQuery和Angular在一起并不是一个很好的做法。但是如果你坚持使用像你提到的选择库这样的jquery插件,那么最好的办法就是用angular中的那个库编写一个指令。

然而,在这种情况下,可以给出一个更简单的解决方案来满足您的要求,但这不是最好的实现。最佳实现是编写一个通用指令。

为什么您的选择插件不适用于路线导航,而且页面刷新工作非常简单。页面刷新时,您包含的选择库将运行所有可用的dom元素,并应用必要的执行以使选择工作。但是当你使用角度路由器远离它时,新渲染的页面不会经历上述过程。因此,选择不起作用。

最简单的解决方案是在school.component.ts中实现生命周期钩子接口AfterViewInit,并在函数的实现中添加这行代码。

$('.selectpicker').selectpicker({
  style: 'btn-info',
  size: 4
});

应该这样做