![](/img/trans.png)
[英]TypeError: 'undefined' is not a function (evaluating 'angular.element(window).width()')
[英]Angular5 jQuery function evaluating as undefined but not in devTools
使用jQuery函數時,我在Angular5中遇到一種奇怪的問題,在我的情況下,這是select2庫
事實是,我在帶有代碼的動態渲染組件中使用它:
@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
完全相同) 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
,該腳本已加載
查看代碼,並經過許多其他嘗試,我已經解決了該問題。 我的ScriptsLoaderService
(由於ScriptsLoaderService
,之所以沒有發布)正在將所有捆綁的腳本加載到scripts.bundle.js
,創建了jQuery實例和所有其他庫。
在動態創建的組件內部,我在所有導入中都使用jQuery,如下所示:
import $ = require('jquery')
那就是為組件范圍創建另一個jQuery實例。
顯然,它沒有我需要的所有庫(這就是Chrome DevTools擁有它們的原因)
我已經解決了,只需將上面的代碼替換為此
declare var jQuery
其中引用全局元素。
我知道,但是我不認為這是我的問題
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.