Angular 4 jQuery不起作用 [英] Angular 4 jquery doesn't work

查看:81
本文介绍了Angular 4 jQuery不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将jQuery用于我的Angular 4应用程序.我已经按照所有步骤在Angular 4上安装了jquery,但是jquery仍然无法正常工作. 我已经将jquery代码放在这样的组件上.

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

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

我的HTML如下 home.component.html

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>

但是,当我单击<h2 id="showAppinfo">Basic App-info</h2>时,什么也没有发生.你能告诉我我是否在正确的地方使用jQuery代码吗?问题出在代码上还是在jQuery安装上?

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

推荐答案

基本问题是您试图在构造函数中操作模板.但是,当您的组件构造函数执行时,#showAppinfo#appInfo元素尚不存在,因为尚未构建视图.

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.

依赖视图元素的操作需要最早在 ngAfterViewInit生命周期挂钩

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
}

您可以使用console.log($("#showAppinfo"))之类的东西对其进行测试,您会发现它不记录任何元素constructor(),但它在ngAfterViewInit()

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

这篇关于Angular 4 jQuery不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆