jQuery With Angular

A question has been in my mind ever since Angular 2+ was released - Can jQuery be used with Angular? In this blog, I will show you how to call a jQuery function from your Angular component to harness the power of jQuery as well as the ease of use.

Create a JavaScript file under any folder of your choice, normally (assets).
  1. $(document).ready(function(){  
  2.   
  3.       
  4.     showAlertMessage= () => {  
  5.   
  6.         $('#message').fadeIn(3000).fadeOut(3000);  
  7.     }  
  8.   
  9.        
  10.  })  

Then, add a reference to this script file inside scripts array (inside - .angular-cli.json) file.

  1. "scripts": [  
  2.         "app/shared/scripts/jquery.scripts.js"  
  3.       ]  

Create injectable service for Window Reference.

  1. import { Injectable } from '@angular/core';  
  2.   
  3. function _window() : any {  
  4.      
  5.    return window;  
  6. }  
  7. @Injectable()  
  8. export class WindowRef {  
  9.    get nativeWindow() : any {  
  10.       return _window();  
  11.    }  
  12. }  

Now, let's move to component code wherein a record insertion is done. We need to show the alert after the new record is inserted. Notice, here is a piece of code to handle the service only. 

  1. import { WindowRef } from "../shared/services/window.service";  
  2.   
  3. constructor(private winRef: WindowRef) { }  
Assume, we have a method that delivers the server to our object to add to the database and then, shows the alert.
  1. add() {  
  2.           
  3.         this.myService.create(this.dataToAdd).subscribe(  
  4.             response=> {  
  5.                 this.winRef.nativeWindow.showAlertMessage();  
  6.             },  
  7.             error=>{  
  8.                 console.log(error);                 
  9.             }  
  10.         );  
  11. }  
Notice

jQuery method is attached to window object as we use jQuery document function.
  1. $(document).ready(function(){}   )  
Good luck and enjoy :)