1

This is a jquery code in my HTML template. I am using a HTML template and sliced it to different components and created an angular project.

   //  class add mouse hover
   jQuery('.custom-nav > li').hover(function(){
      jQuery(this).addClass('nav-hover');
   }, function(){
      jQuery(this).removeClass('nav-hover');
   });

This code is not working.

The file is saved in a folder named assets inside node_modules as scripts_custom.js. The file is included in angular.json.

I am new to angular6. Please do help me to correct it.

Suraj Kumar
  • 5,547
  • 8
  • 20
  • 42

4 Answers4

2

It not a good practice to include jquery in angular project but still you want to use it you can write declare $ any in component file after all import section

Please let me know if it solves your problem

Ankur Shah
  • 412
  • 6
  • 16
1

I agree with @Ankur Shah it is not good practice to use Jquery in an angular project. Instead, you can use a custom directive or use (mouseenter) and (mouseleave) event.

Check the link below toggleclass

1

To include jQuery code into your component do the following steps:

step 1: Add jQuery into your index.html

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"> 
</script>

step 2: Declare jQuery into your component where you want to add that code as follows

import { Component } from '@angular/core';
declare var jquery:any;
declare var $ :any;

@Component({
 selector: 'app-root',
 templateUrl: './app.component.html',
 styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'angular 4 with jquery';
  //Add jQuery here
}

Hope this will work for you. Thanks

Sneha Pawar
  • 1,097
  • 6
  • 14
1

This video helped me to solve the issue.

https://www.youtube.com/watch?v=IlgsWcYnPdo

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  title = 'frontend';
  ngOnInit(){
    $(document).ready(function(){
    //  class add mouse hover
    jQuery('.custom-nav > li').hover(function(){
      jQuery(this).addClass('nav-hover');
      }, function(){
        jQuery(this).removeClass('nav-hover');
      });
    });
  }
}

Hope this is a good way to solve it. Thanks all.