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).
- $(document).ready(function(){
-
-
- showAlertMessage= () => {
-
- $('#message').fadeIn(3000).fadeOut(3000);
- }
-
-
- })
Then, add a reference to this script file inside scripts array (inside - .angular-cli.json) file.
- "scripts": [
- "app/shared/scripts/jquery.scripts.js"
- ]
Create injectable service for Window Reference.
- import { Injectable } from '@angular/core';
-
- function _window() : any {
-
- return window;
- }
- @Injectable()
- export class WindowRef {
- get nativeWindow() : any {
- return _window();
- }
- }
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.
- import { WindowRef } from "../shared/services/window.service";
-
- 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.
- add() {
-
- this.myService.create(this.dataToAdd).subscribe(
- response=> {
- this.winRef.nativeWindow.showAlertMessage();
- },
- error=>{
- console.log(error);
- }
- );
- }
Notice
jQuery method is attached to window object as we use jQuery document function.
- $(document).ready(function(){} )
Good luck and enjoy :)