我目前正在使用带有jQuery的Angular 2,jQuery被连接成一个单独的文件。此文件存在于许多范围之外,范围只是一个文档就绪函数,每个特定元素都有
当在正确的页面上重新加载浏览器时,代码执行得非常好,因为它真正找到了文档准备好的元素,但是当从另一个页面导航时,代码不会运行。
我尝试通过在app组件中设置ngAfterViewInit()
解决问题,在那里加载脚本而不是像index这样在index.html:
export class AppComponent implements AfterViewInit{
ngAfterViewInit() {
$( document ).ready(function() {
$.getScript( "library/js/main.min.js" );
});
}
}
代码再次仅在重新加载特定页面时执行,我是否需要在每个组件上添加此ngAfterViewInit()
?
解决方案是Router
事件监听器;此代码段中的代码将侦听路由器中的更改(在NavigationEnd
实例上进行过滤),然后执行内部代码,它将使用jQuery检索JavaScript文件。
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');
});
}
}
每条路线改变执行jQuery
的方法是:
脚本必须链接到index.html
在你的scritps.js
中添加一个函数:
function init_plugins() { // add function
$(function() { //normal js scritps
"use strict";
$(function() {
$(".preloader").fadeOut();
});
/* more stuff */
});
}
现在在你的Component
中声明新函数并在你的ngOnInit
中执行如下:
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 */
}
然后,当您更改路径并加载component.html时,将执行脚本。
干杯