javascriptangularwebangular-componentsangular-component-router

scripts in Angular 4 not working after change view


In my angular 4 app I have some script, when I load the first time all its ok, but when change view to other component of my app and return to main page all its broken the scripts not work. in the console log send message for example this a function scroll top

$(window).scroll(function() {
var wScroll = $(this).scrollTop(), scrollAmount = 150;

if (wScroll > scrollAmount) {
  $(".button__scroll--up").addClass("is_showing");
} else {
  $(".button__scroll--up").removeClass("is_showing");
}

});

$('.button__scroll--up').click( function(){
$('html , body').animate({scrollTop: 0},1000);
})  

and the console log send this

Uncaught TypeError: Cannot read property 'top' of undefined
at HTMLDivElement.<anonymous> (efects-styles.js:58)
at HTMLDivElement.dispatch (jquery.min.js:3)
at HTMLDivElement.r.handle (jquery.min.js:3)
at ZoneDelegate.webpackJsonp.../../../../zone.js/dist/zone.js.ZoneDelegate.invokeTask (polyfills.bundle.js:2839)
at Zone.webpackJsonp.../../../../zone.js/dist/zone.js.Zone.runTask (polyfills.bundle.js:2606)
at ZoneTask.webpackJsonp.../../../../zone.js/dist/zone.js.ZoneTask.invokeTask [as invoke] (polyfills.bundle.js:2913)
at invokeTask (polyfills.bundle.js:3779)
at HTMLDivElement.globalZoneAwareCallback (polyfills.bundle.js:3797

pleas help me, thanks!!


Solution

  • This is because Angular only loads DOM elements that are in the initial view. You will need to write a script that will rerun your scripts on route change.

    The method I have for this problem is to bind to router events, and when a route changes, use jQuery AJAX to fetch the script, and run the result.