在路由更改时在Angular 2中执行jQuery

问题描述 投票:1回答:2

我目前正在使用带有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()

angular angular2-routing
2个回答
2
投票

解决方案是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');
        });
    }
}

-1
投票

每条路线改变执行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时,将执行脚本。

干杯

© www.soinside.com 2019 - 2024. All rights reserved.