I'm currently developing an Angular4 application and I want to import some javascript libraries but just for a single component.
Currently I can easily import this libraries by defining their paths inside .angular-cli.json like that:
{
"scripts": [
"../node_modules/jquery/dist/jquery.min.js",
"../node_modules/jqueryui/jquery-ui.js",
"../src/assets/js/jquery/cometd/org-cometd.js",
"../src/assets/js/jquery/cometd/jquery.cometd.js",
],
...
}
However, the mentioned scripts will be imported for all the application. Is there a way to import them just for a specific component ? I've tried to import them inside the component like shown below but without success.
import { Component, OnInit, ViewEncapsulation, Inject } from '@angular/core';
...
import "../../../../../node_modules/jquery/dist/jquery.min.js";
import "../../../../../node_modules/jqueryui/jquery-ui.js";
import "../../../../assets/js/jquery/cometd/org-cometd.js";
import "../../../../assets/js/jquery/cometd/jquery.cometd.js";
@Component({
selector: '...',
templateUrl: '...',
styleUrls: '...',
encapsulation: ViewEncapsulation.None
})
export class MyComponent implements OnInit {
...
}
[UPDATE] - I forgot to mention that I am currently using the ViewEncapsulation.None to be able to apply the styles from some css files into the component. Not sure if this detail can be related with the issue.
Things like jQuery and bootstrap are global and will be available to the application. But, it is good practice to make them injectable and thus referable from single components.
First install jQuery
npm install --save jquery
npm install -D @types/jquery
Second make an injection module
import { NgModule } from '@angular/core';
import { InjectionToken } from '@angular/core';
import * as jquery from 'jquery';
export const JQUERY = new InjectionToken<jquery>('jQuery');
export function _jquery(): jquery {
return jquery;
}
@NgModule({
providers: [{
provide: JQUERY,
useFactory: _jquery
}]
})
export class JqueryTokenModule { }
Third, in your module:
providers: [{provide: JQUERY, useValue: _jquery}]
Finally, inject it into your component
constructor(@Inject(JQUERY) private $) {
// use `this.$` which is jQuery
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With