Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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)
like image 677
Squapl Recipes Avatar asked Jul 03 '17 04:07

Squapl Recipes


1 Answers

Solved it after a lot of iteration. Solution: If you are importing the js in angular-cli.json then no need to import the same again in components. Results in duplication and you will get weird javascript exceptions which will mislead. Just declare them and use it like the code below.

declare let $ : any;

additionally in Onngint() {} method call the javascript function once again. This has to be called in each and every component this function will be used. example below:

    ngOnInit() {
        $(function(){
            $('.button-collapse').sideNav();
        }); // end of document ready
    }

Remember to check document ready. Not checking resulted in early execution of scripts.

like image 106
Squapl Recipes Avatar answered Nov 15 '22 04:11

Squapl Recipes