admin管理员组

文章数量:1303343

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 ponent like this.

homeponent.ts

import * as jQuery from 'jquery'
import { Component, OnInit } from '@angular/core';


 @Component({
  selector: 'app-home',
  templateUrl: './homeponent.html',
  styleUrls: ['./homeponent.css']
})
export class HomeComponent implements OnInit {

constructor(db: AngularFireDatabase,public authService: AuthService,public 
afAuth: AngularFireAuth,) { 
$(document).ready(function(){
  $("#showAppinfo").click(function(){
      $("#appinfo").slideToggle();
  });
});
ngOnInit()
{}
}

And my Html is the following homeponent.html

    <h1>This is Home page!!</h1>
    <h2 id="showAppinfo">Basic App-info</h2>
    <ul class="list-group" id="appinfo">
      <li class="list-group-item">Publiser: {{ (appinfo | async)?.Publisher }}</li>
      <li class="list-group-item">Publication_Year: {{ (appinfo | async)?.Publication_Year }}</li>
      <li class="list-group-item">Version: {{ (appinfo | async)?.Version }}</li>
      <li class="list-group-item">Registered Users: {{ (appinfo | async)?.Rusers }}</li>
      <li class="list-group-item">Languages: {{ (appinfo | async)?.Language }}(Only)</li>
   </ul>

But nothing happens when I click on <h2 id="showAppinfo">Basic App-info</h2>. Can you tell my if I am using the jquery code in the correct place?? The problem is on code or on the jquery instalation??

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 ponent like this.

home.ponent.ts

import * as jQuery from 'jquery'
import { Component, OnInit } from '@angular/core';


 @Component({
  selector: 'app-home',
  templateUrl: './home.ponent.html',
  styleUrls: ['./home.ponent.css']
})
export class HomeComponent implements OnInit {

constructor(db: AngularFireDatabase,public authService: AuthService,public 
afAuth: AngularFireAuth,) { 
$(document).ready(function(){
  $("#showAppinfo").click(function(){
      $("#appinfo").slideToggle();
  });
});
ngOnInit()
{}
}

And my Html is the following home.ponent.html

    <h1>This is Home page!!</h1>
    <h2 id="showAppinfo">Basic App-info</h2>
    <ul class="list-group" id="appinfo">
      <li class="list-group-item">Publiser: {{ (appinfo | async)?.Publisher }}</li>
      <li class="list-group-item">Publication_Year: {{ (appinfo | async)?.Publication_Year }}</li>
      <li class="list-group-item">Version: {{ (appinfo | async)?.Version }}</li>
      <li class="list-group-item">Registered Users: {{ (appinfo | async)?.Rusers }}</li>
      <li class="list-group-item">Languages: {{ (appinfo | async)?.Language }}(Only)</li>
   </ul>

But nothing happens when I click on <h2 id="showAppinfo">Basic App-info</h2>. Can you tell my if I am using the jquery code in the correct place?? The problem is on code or on the jquery instalation??

Share asked Jul 23, 2017 at 21:38 Vasilis MichailVasilis Michail 4032 gold badges6 silver badges19 bronze badges 7
  • are you using angular-cli? and you should have import * as $ from 'jquery' if you want to use it as usual – 0mpurdy Commented Jul 23, 2017 at 21:45
  • did you set jquery on angular-cli.json ? – Marcogomesr Commented Jul 23, 2017 at 21:47
  • I found a link which explained how to install jquery on angular 4 I did all the steps.So the code is fine and the problem is in installation?? – Vasilis Michail Commented Jul 23, 2017 at 21:49
  • Yes i am using angular-cli I changed my import to import * as $ from 'jquery' all I had set jquery on angular-cli.json but still dont work.. – Vasilis Michail Commented Jul 23, 2017 at 21:53
  • I assume that your angular-cli.json has a correct path to the jquery* library? – Zze Commented Jul 23, 2017 at 22:40
 |  Show 2 more ments

6 Answers 6

Reset to default 2

The basic problem is that you're trying to manipulate your template in the constructor. But when your ponent 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

export class HomeComponent implements OnInit, 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()

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';

export const JQUERY_TOKEN = new InjectionToken<JQueryStatic>('jquery');

export function jQueryFactory() {
    return $;
}

export const JQUERY_PROVIDER = { provide: JQUERY_TOKEN, useFactory: jQueryFactory };

Add the Provider in Module:

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

Use DI in any ponent:

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

Be happy :D

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

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>
  <script src="https://code.jquery./jquery-3.2.1.min.js"></script>
</body>
...

2nd Step

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

Go to your desired ponents .ts script.

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

// this line will allow you to use jQuery
declare var $: any;

@Component({
  ...
})

3rd Step

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

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

export class TestComponent implements OnInit {

  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

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.ponent.html',
  styleUrls: ['./navbar.ponent.scss']
})
export class NavbarComponent implements OnInit, 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');
    // });
  }

}

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();
}

your onInit method was inside the constructor, try it in the following way

constructor(db: AngularFireDatabase, public authService: AuthService, public afAuth: AngularFireAuth) {
    $(document).ready(function () {
        $("#showAppinfo").click(function () {
            $("#appinfo").slideToggle();
        });
    });

}
ngOnInit() { }}

本文标签: javascriptAngular 4 jquery doesn39t workStack Overflow