Search code examples
javascriptangulartypescriptangular4-router

Angular 5. How to track route change in Javascript file, or execute function in component level?


I have global.js script file and need to launch InitSwiper() function when route changes to '/home', but can't find how to track router in script file or launch function through home.component.ts

import { Component, OnInit } from '@angular/core';

declare var global: any; 

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

  ngOnInit() {
    global.initSwiper();
  }

}

global.js

$(function () {

    "use strict";
    $(window).load(function(){
        pageCalculations();
        $('#loader-wrapper').fadeOut();
        $('body').addClass('loaded');
        initSwiper();
    });
...
})

Solution

  • If you are using CLI, you need to include that file in .angular-cli.json file inside "scripts" array.

    if you want to call a function from that file in home.component.ts only, then you can declare as below

    declare var global:any; 
    

    and then on

    ngOnInit(){
        global.InitSwiper();
    }
    

    Some have suggested guards, but it's overkill if you don't need to delay or prevent the route from being loaded.