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. showAlertMessage= () => {
  3. $('#message').fadeIn(3000).fadeOut(3000);
  4. }
  5. })

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. function _window() : any {
  3. return window;
  4. }
  5. @Injectable()
  6. export class WindowRef {
  7. get nativeWindow() : any {
  8. return _window();
  9. }
  10. }

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. 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. this.myService.create(this.dataToAdd).subscribe(
  3. response=> {
  4. this.winRef.nativeWindow.showAlertMessage();
  5. },
  6. error=>{
  7. console.log(error);
  8. }
  9. );
  10. }
Notice

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