Angular4: jQuery and angular2-materialize not working after route navigation

Viewed 1671

Have created an angular 4 project with angular-cli. imported css and js in angular-cli.json file.

"styles": [
    "../node_modules/materialize-css/dist/css/materialize.css",
    "styles.css"
],
"scripts": [
    "../node_modules/jquery/dist/jquery.js",
    "../node_modules/hammerjs/hammer.js",
    "../node_modules/materialize-css/dist/js/materialize.js",
    "../src/assets/js/init.js"
],

init.js has below functions

(function($) {
    $(function() {
        $('.slider').slider();
        $('.button-collapse').sideNav();
        $('.carousel').carousel();
        // $('.carousel.carousel-slider').carousel({fullWidth: true});
        $('.carousel').carousel({
            dist: 0,
            shift: 0,
            padding: 20,
        });

    }); // end of document ready
})(jQuery);

imported MaterializeModule in app.module.ts import { MaterializeModule } from 'angular2-materialize';

Slider works as expected when we land page first time or when we refresh.

Problem: when we navigate using router-link then page navigates correctly but javascript functions are not getting called.

routing from home page <a routerLink="/blog/abc-1">Blog</a>

I tried: ` blog.component.ts

import { Component, OnInit } from '@angular/core';
import { MaterializeModule } from 'angular2-materialize';

import * as $ from 'jquery';

import * as Materialize from 'materialize-css';


declare let Materialize : any;

@Component({
  selector: 'app-blog',
  templateUrl: './blog.component.html',
  styleUrls: ['./blog.component.css']
})
export class BlogComponent implements OnInit {

  constructor() { }

  ngOnInit() {
    Materialize('.slider').slider();
  }

}

` Error: getting error : ERROR TypeError: a.addEventListener is not a function

at http://localhost:4200/vendor.bundle.js:15611:765
at Array.forEach (native)
1 Answers
Related