0

I have added some 3rd party Libraries.(Bootstrap,Jquery and boot-strap-select (http://silviomoreto.github.io/bootstrap-select/))

When I'm navigating pages "boot-strap-select" is not working. But when I refresh the page it works. But I'm wonder how bootstrap is working without refreshing.

I installed the library using npm and defined in 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"
  ]

I have tried to recreate script element in DOM but it refreshing the page (Links mentioned below).

Load scripts through all components in Angular 2

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

I want to load third Party Library without refreshing the page when navigating.

Source code : RepoLink

progman
  • 376
  • 6
  • 15

1 Answers1

0

What you need to understand is, JQuery and Angular together is not a very good practice. But If you insist on working with a jquery plugin like the select library you have mentioned, Then the best thing to do is writing a directive using that library in angular.

However in this case, A simpler solution could be given to achieve your requirement, but it's not the best implementation. Best implementation is writing a common directive.

Why your select plugin doesn't work on route navigation and works on page refresh is pretty simple. When the page refreshes, The select library you have included runs through all the available dom elements and applies the necessary executions to get the select working. But when you navigate away from it using the angular router, The newly rendered page, doesn't go through the above mentioned process. Hence the select will not work.

Simplest solution is implementing the lifecycle hook interface AfterViewInit in your school.component.ts and in the implementation of the function add this line of code.

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

That should do it

nilesh93
  • 419
  • 3
  • 17