Angular 4 jquery doesn't work

Viewed 4058

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

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 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??

6 Answers

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']
})
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');
    // });
  }

}

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() { }}
Related