Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Import 3rd party javascript libraries in Angular single components

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.

like image 989
David R Avatar asked Dec 10 '25 12:12

David R


1 Answers

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
}
like image 153
mgm87 Avatar answered Dec 12 '25 09:12

mgm87



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!