简体   繁体   English

Angular 4 jQuery不起作用

[英]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. 我正在尝试对Angular 4应用程序使用jquery。我已经按照所有步骤在Angular 4上安装了jquery,但是jquery仍然无法正常工作。 I had put the jquery code on the component like this. 我已经将jQuery代码放在这样的组件上。

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

And my Html is the following home.component.html 我的HTML是以下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> . 但是,当我单击<h2 id="showAppinfo">Basic App-info</h2>时,什么也没有发生。 Can you tell my if I am using the jquery code in the correct place?? 你能告诉我我是否在正确的地方使用jQuery代码吗? The problem is on code or on the jquery instalation?? 问题出在代码上还是在jQuery安装上?

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. 但是,当您的组件构造函数执行时, #showAppinfo#appInfo元素尚不存在,因为尚未构建视图。

Operations that depend on view elements need to be performed at the earliest in the ngAfterViewInit lifecycle hook 依赖视图元素的操作需要尽早在ngAfterViewInit生命周期挂钩中执行

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

Following the steps that works for me: 遵循对我有用的步骤:

Install jquery npm install jquery 安装jQuery NPM安装jQuery

Install ts type npm install @types/jquery 安装ts类型npm install @ types / jquery

Add jquery.min.js in your .angular-cli.json: 在您的.angular-cli.json中添加jquery.min.js:

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

Create a service to JQuery with the Token, Provider and Factory: 使用令牌,提供者和工厂为JQuery创建服务:

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 component: 在任何组件中使用DI:

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

Be happy :D 开心点:D

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

Easiest and Shortest way possible to use jQuery in Angular 2/4 在Angular 2/4中使用jQuery的最简便方法

1st Step 第一步

From index.html 来自index.html

my-test-project\\src\\index.html my-test-project \\ src \\ index.html

Type jQuery cdn below app-root tag. app-root标记下输入jQuery CDN。

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

2nd Step 第二步

my-test-project\\src\\app\\test\\test.component.ts 我的测试项目\\ src \\ app \\ test \\ test.component.ts

Go to your desired components .ts script. 转到所需的组件.ts脚本。

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.component.ts 我的测试项目\\ src \\ app \\ test \\ test.component.ts

Test jQuery by logging 'I<3Cats' inside jQuery syntax $(() => { /* content here */ }) . 通过在jQuery语法$(() => { /* content here */ })记录'I<3Cats'测试jQuery。

export class TestComponent implements OnInit {

  constructor() { }

  ngOnInit() {
    $(() => {
      console.log('hello there!');
    });
  }

}

You can also use this technique with other javscript libraries. 您也可以将此技术与其他javscript库一起使用。 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... 我在无法在引导导航栏上使用jquery遇到问题并像这样解决了...

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

}

Not sure what slideToggle() is doing, but FYI in Angular if you added #ref to h2.. you can then add 不知道slideToggle()在做什么,但是如果您在h2中添加了#ref,则可以在Angular中使用FYI。

@ViewChild('ref')
h2El:Element;

in Typescript associated to the HTML. 与HTML关联的Typescript中。 to do equivalent of $("#showAppinfo").. 做等效于$(“#showAppinfo”)..

If you used this in the HTML 如果您在HTML中使用了此功能

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

you'd have click handler.. so in Typescript add 您将拥有点击处理程序..因此,在Typescript中添加

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

your onInit method was inside the constructor, try it in the following way 您的onInit方法位于构造函数内部,请按以下方式尝试

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

}
ngOnInit() { }}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM