Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
79
rated 0 times [  85] [ 6]  / answers: 1 / hits: 18453  / 7 Years ago, tue, february 28, 2017, 12:00:00

I use jQuery-based select2 component in my AngularJS project. I had similar issue as guys here: https://github.com/fronteed/icheck/issues/322, and solved it using advice from there. To be accurate, I received error TypeError: $(...).select2 is not a function when not using that advice.



i.e. I added next lines to configuration of Webpack in @angular/cli/models/webpack-configs/common.js.



plugins: [
new webpack.ProvidePlugin({
$: jquery,
jQuery: jquery
})
]


Is it the best possible way to enable jQuery in angular/cli?



I don't think that doing same as in https://github.com/angular/angular-cli/wiki/stories-global-lib is correct way, because



a) webpack bundles jQuery without need to specify it in scripts



b) it still throws TypeError: $(...).select2 is not a function error when you include it as described in story.


More From » jquery

 Answers
41

I was able to achieve what I needed by exposing Webpack. Use ng eject command.



First, install jQuery using npm install -S jquery (and I also installed npm install -S select2, because I needed that too).



Then, make sure that you made backup of your package.json file, since during ng eject Angular CLI will try to add its Webpack dependencies inside your package.json.



After ng eject finished working, inside webpack.config.js I added



// ... Inside require/imports part
const ProvidePlugin = require('webpack/lib/ProvidePlugin');

// ... Inside `plugins` section of Webpack configuration
new ProvidePlugin({
$: jquery,
jQuery: jquery
})


And now select2 adds $(...).select2 function to global jQuery object properly!



To use jQuery with select2 inside your .ts file, you can add next lines at the beginning of that file:



import select2;
import jquery;
declare var $: any;

// Somewhere deep within component
// ...

$(this.input.nativeElement)
.select2(config)
.on(change select2:select select2:unselect, (e: any) => this.onSelect2ElementChange(e));

// ...

[#58742] Sunday, February 26, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
raveno

Total Points: 453
Total Questions: 92
Total Answers: 92

Location: France
Member since Thu, Oct 27, 2022
2 Years ago
raveno questions
;