Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 559
Vasilis Michail Avatar asked Jul 23 '17 21:07

Vasilis Michail


1 Answers

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

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

like image 50
BeetleJuice Avatar answered Sep 27 '22 19:09

BeetleJuice