0

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!!

wolf
  • 127
  • 1
  • 10
Andy Torres
  • 189
  • 1
  • 11
  • 1. This is not a minimal verifiable example; [please read](https://stackoverflow.com/help/mcve) 2. You should render the DOM using Angular functionalities – Dani Grosu Aug 07 '17 at 10:00

1 Answers1

1

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.

wilsonhobbs
  • 941
  • 8
  • 18
  • thanks wilsonhobbs It was very helpful, i solved the problem whit your instruction and other way, was include javascript files in the onInit method, thanks again!! – Andy Torres Aug 08 '17 at 03:08
  • If this answer helped, I would really appreciate you marking it as answered :) thanks – wilsonhobbs Aug 08 '17 at 17:11
  • @AndyTorres Torres how u include javascript files in the onInit method..could u explain? – RamAnji Sep 22 '17 at 13:12
  • 1
    @RamAnji only put this $.getScript('route/of/your/file.js'); i hope this works for you – Andy Torres Sep 27 '17 at 21:16
  • @RamAnji sorry i forget first to all install this npm install jquery --save npm install @types/jquery -D and add this in the component where you will use js import * as $ from 'jquery'; – Andy Torres Sep 27 '17 at 22:14