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)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With