问题
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