Angular 4 jquery not working

I am trying to use jquery for my Angular 4 app. I followed all the steps to install jquery on my Angular 4. Although jquery still doesn't work. I have put jquery code on component as follows.

home.component.ts

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


 @Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.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.component.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 <h2 id="showAppinfo">Basic App-info</h2>

. Can you tell me if I am using jquery code in the right place? Is the problem with the code or jquery installation?

+3


source to share


5 answers


The main problem is when you are trying to manipulate your template in the constructor. But when your component constructor is executed, the elements #showAppinfo

and #appInfo

do not exist yet because the view has not been created.

Operations that depend on view items should be done as soon as possible in ngAfterViewInit

hook>



export class HomeComponent implements OnInit, OnAfterViewInit 
...

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

      

You can test this with console.log($("#showAppinfo"))

and you will see that it does not register any item constructor()

, but it does it inngAfterViewInit()

+1


source


Following the steps that work for me:

Install jquery npm install jquery

Install type ts npm install @ types / jquery

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

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

      

Create a Service for JQuery with 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 to the 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')

      

+1


source


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

@ViewChild('ref')
h2El:Element;

      

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

If you used this in HTML

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

      

you will have a click handler. so in Typescript add

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

      

0


source


Easiest and shortest way to use jQuery in Angular 2/4

1st step

From index.html

my test project \ src \ index.html

Enter jQuery cdn below the tag app-root

.

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

      

Step 2

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

Navigate to the components you want .ts script.

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

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

@Component({
  ...
})

      

Third step

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

Validate 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 it is safe, but it will definitely help. quite

0


source


your onInit method was inside constructor, try it like this

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

}
ngOnInit() { }}

      

0


source







All Articles