Executing jQuery each in Angular 2 on route change

混江龙づ霸主 提交于 2021-02-07 10:37:18

问题


I am currently using Angular 2 with jQuery, the jQuery is concatenated into a separate file. This file exists out of many scopes, the scope is simply an on document ready function with an each on specific elements

When reloading the browser on the correct page the code gets executed perfectly fine because it truly finds the elements on document ready, however when navigating from another page the code does not run.

I tried working around the problem by setting an ngAfterViewInit() in the app component, loading the script there instead of in the index.html like this:

export class AppComponent implements AfterViewInit{
    ngAfterViewInit() {
        $( document ).ready(function() {
            $.getScript( "library/js/main.min.js" );
        });
    }
}

The code is again only executing when reloading on that specific page, do I need to add this ngAfterViewInit() on every single component?


回答1:


The solution was a Router event listener; the code in this snippet will listen to changes in the router (which are filtered on instances of NavigationEnd) and then executes the code inside, it retrieves a JavaScript file with jQuery.

import { Component, OnInit } from '@angular/core';
import { Router, NavigationEnd, ActivatedRoute } from '@angular/router';

import 'rxjs/add/operator/filter';
import 'rxjs/add/operator/map';

declare var $:any;

export class AppComponent implements OnInit {
    constructor(
        private router: Router,
        private activatedRoute: ActivatedRoute
    ) { }

    ngOnInit() {
        this.router.events
        .filter(event => event instanceof NavigationEnd)
        .map(() => this.activatedRoute)
        .subscribe((event) => {
            $.getScript('library/js/main.min.js');
        });
    }
}



回答2:


The way to execute jQuery by each routes change is:

The scripts must be linked to the index.html In your scritps.js add a function:

function init_plugins() { // add function

    $(function() {        //normal js scritps
        "use strict";
        $(function() {
            $(".preloader").fadeOut();
        });

        /* more stuff */

    });

}

Now in your Component declare the new function and execute in your ngOnInit like this:

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

declare function init_plugins(); // declare scripts

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

  constructor() { }

  ngOnInit() {
    init_plugins(); // execute scripts
  }

  /* more stuff */
}

Then, when you change the path and load the component.html, the scripts will be executed.

Cheers



来源:https://stackoverflow.com/questions/41226910/executing-jquery-each-in-angular-2-on-route-change

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!