Skip to content Skip to sidebar Skip to footer

Angular 4 Jquery Doesn't Work

I am trying to use jquery to my Angular 4 app.I had followed all the steps to install jquery on my Angular 4.However jquery still dont work. I had put the jquery code on the compon

Solution 1:

The basic problem is that you're trying to manipulate your template in the constructor. But when your component constructor executes, #showAppinfo and #appInfo elements don't exist yet because the view has not been built.

Operations that depend on view elements need to be performed at the earliest in the ngAfterViewInit lifecycle hook

exportclassHomeComponentimplementsOnInit, OnAfterViewInit 
...

ngAfterViewInit(){
  // do your template manipulation here
}

You can test this with something like console.log($("#showAppinfo")) and you'll see that it doesn't log any element constructor(), but it does in ngAfterViewInit()

Solution 2:

Following the steps that works for me:

Install jquery npm install jquery

Install ts type npm install @types/jquery

Add jquery.min.js in your .angular-cli.json:

"scripts":["../node_modules/jquery/dist/jquery.min.js"]

Create a service to JQuery with the Token, Provider and Factory:

import { InjectionToken } from'@angular/core';
import * as $ from'jquery';

exportconstJQUERY_TOKEN = newInjectionToken<JQueryStatic>('jquery');

exportfunctionjQueryFactory() {
    return $;
}

exportconstJQUERY_PROVIDER = { provide: JQUERY_TOKEN, useFactory: jQueryFactory };

Add the Provider in Module:

@NgModule({
  declarations: [
    ...
  ],
  providers: [
    JQUERY_PROVIDER,
    ...
  ]
})

Use DI in any component:

constructor(
    @Inject(JQUERY_TOKEN) private $: JQueryStatic
  )

Be happy :D

this.$('body').css('background-color', 'red')

Solution 3:

Easiest and Shortest way possible to use jQuery in Angular 2/4

1st Step

From index.html

my-test-project\src\index.html

Type jQuery cdn below app-root tag.

...
<body><app-root></app-root><scriptsrc="https://code.jquery.com/jquery-3.2.1.min.js"></script></body>
...

2nd Step

my-test-project\src\app\test\test.component.ts

Go to your desired components .ts script.

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

// this line will allow you to use jQuerydeclarevar$: any;

@Component({
  ...
})

3rd Step

my-test-project\src\app\test\test.component.ts

Test jQuery by logging 'I<3Cats' inside jQuery syntax $(() => { /* content here */ }).

exportclassTestComponentimplementsOnInit {

  constructor() { }

  ngOnInit() {
    $(() => {
      console.log('hello there!');
    });
  }

}

You can also use this technique with other javscript libraries. I don't know if this is safe but will sure help you. quite

Solution 4:

i had an issue with jquery not working on bootstrap navbar and solved like this...

import { Component, OnInit, AfterViewInit, ElementRef } from'@angular/core';
//declare var $: any; //old code..@Component({
  selector: 'app-navbar',
  templateUrl: './navbar.component.html',
  styleUrls: ['./navbar.component.scss']
})
exportclassNavbarComponentimplementsOnInit, AfterViewInit {

  constructor(private elem: ElementRef) { }

  ngOnInit() {
  }
  ngAfterViewInit() {
    this.elem.nativeElement.querySelectorAll('.navbar-nav>li>a').forEach((el) => {
      el.addEventListener('click', () => {
        this.elem.nativeElement.querySelector('.navbar-toggler').classList.toggle('collapsed');
        this.elem.nativeElement.querySelector('.navbar-collapse').classList.toggle('show');
      });
    })

    //old code...// $('.navbar-nav>li>a').on('click', function () {//   $('.navbar-collapse').collapse('hide');// });
  }

}

Solution 5:

Not sure what slideToggle() is doing, but FYI in Angular if you added #ref to h2.. you can then add

@ViewChild('ref')
h2El:Element;

in Typescript associated to the HTML. to do equivalent of $("#showAppinfo")..

If you used this in the HTML

<h2 #ref (click)="handler()">...</h2>

you'd have click handler.. so in Typescript add

handler() {
 this.h2El.slideToggle();
}

Post a Comment for "Angular 4 Jquery Doesn't Work"