Angular5 jQuery函数评估为未定义但未在devTools中

时间:2018-03-08 08:53:38

标签: javascript jquery angular5

使用jQuery函数时,我遇到了一个奇怪的问题,在我的例子中,它是select2 library

事实是我在动态渲染的组件中使用它,其代码为:

当前代码状态

@ViewChild('mainCountry') mainCountrySelect: ElementRef;
@ViewChild('compareCountry') compareCountrySelect: ElementRef;

ngAfterViewInit() {
    const mainSelectNE = this.mainCountrySelect.nativeElement;
    const mainSelectID = mainSelectNE.getAttribute('id');

    const compareSelectNE = this.compareCountrySelect.nativeElement;
    const compareSelectID = compareSelectNE.getAttribute('id');

    console.log(
        'Main ID: ' + mainSelectID,
        'Main EL: ', $(mainSelectNE),
        'Compare ID: ' + compareSelectID,
        'Compare EL: ', $(compareSelectNE)
    );

    (<any>$(mainSelectNE)).select2(defaultSelect2Options);
    (<any>$(compareSelectNE)).select2(defaultSelect2Options);
}

这是我到目前为止所尝试的

除了使用ngAfterContentInit挂钩(与ngAfterViewInit完全相同)之外,我还尝试轮询jQuery以检查函数是否存在,如下所示:

ngAfterViewInit() {
    const mainSelectNE = this.mainCountrySelect.nativeElement;
    const mainSelectID = mainSelectNE.getAttribute('id');

    const compareSelectNE = this.compareCountrySelect.nativeElement;
    const compareSelectID = compareSelectNE.getAttribute('id');

    console.log(
        'Main ID: ' + mainSelectID,
        'Main EL: ', $(mainSelectNE),
        'Compare ID: ' + compareSelectID,
        'Compare EL: ', $(compareSelectNE)
    );

    const funcInterval = setInterval(() => {
        console.log((<any>$.fn).select2);
    },500);

    /*
    (<any>$(mainSelectNE)).select2(defaultSelect2Options);
    (<any>$(compareSelectNE)).select2(defaultSelect2Options);
    */
}

始终返回undefined

我尝试过使用$(document).ready(),但它仍无效。

ngAfterViewInit() {
    const mainSelectNE = this.mainCountrySelect.nativeElement;
    const mainSelectID = mainSelectNE.getAttribute('id');

    const compareSelectNE = this.compareCountrySelect.nativeElement;
    const compareSelectID = compareSelectNE.getAttribute('id');

    console.log(
        'Main ID: ' + mainSelectID,
        'Main EL: ', $(mainSelectNE),
        'Compare ID: ' + compareSelectID,
        'Compare EL: ', $(compareSelectNE)
    );

    // same as $(document).ready()
    $(() => {
        (<any>$(mainSelectNE)).select2(defaultSelect2Options);
        (<any>$(compareSelectNE)).select2(defaultSelect2Options);
    });
}

奇怪的是,如果我尝试在Google Chrome的开发控制台上访问它,它就能正常运行。 $.fn.select2输出它,$('#' + mainSelectID).select2()也可以工作(仍然在devTools中)。并且所有应用程序的脚本都在scripts.bundle.js内加载,并加载

1 个答案:

答案 0 :(得分:0)

查看代码,经过多次尝试后,我已经解决了这个问题。 我的ScriptsLoaderService(我没有发布因为它不相关)是在scripts.bundle.js内加载所有捆绑的脚本,创建jQuery实例和所有其他库。

在动态创建的组件中,我在所有导入中使用jQuery,如下所示:

import $ = require('jquery')

那是为组件范围创建另一个jQuery实例 显然它并没有我需要的所有库(这就是Chrome DevTools拥有它们的原因)

我只是通过用上面的代码替换上面的代码来解决它

declare var jQuery

对全球元素的引用。
我知道,但我并不认为这是我的问题