【问题标题】:Angular 4 jquery doesn't workAngular 4 jquery 不起作用
【发布时间】:2017-12-29 10:08:06
【问题描述】:

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

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

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

但是当我点击&lt;h2 id="showAppinfo"&gt;Basic App-info&lt;/h2&gt; 时没有任何反应。你能告诉我我是否在正确的地方使用了 jquery 代码吗?问题出在代码上还是 jquery 安装上??

【问题讨论】:

  • 你在使用 angular-cli 吗?如果你想像往常一样使用它,你应该有import * as $ from 'jquery'
  • 你在 angular-cli.json 上设置了 jquery 吗?
  • 我找到了一个链接,它解释了如何在 Angular 4 上安装 jquery 我做了所有的步骤。所以代码很好,问题出在安装上??
  • 是的,我正在使用 angular-cli 我将导入更改为 import * as $ from 'jquery' 所有我在 angular-cli.json 上设置的 jquery 但仍然不起作用..
  • 我假设您的angular-cli.json 具有指向 jquery* 库的正确路径?

标签: javascript jquery angular typescript


【解决方案1】:

不确定 slideToggle() 正在做什么,但如果您添加了 Angular 中的仅供参考 #ref 到 h2.. 然后你可以添加

@ViewChild('ref')
h2El:Element;

在与 HTML 关联的 Typescript 中。 相当于 $("#showAppinfo")..

如果你在 HTML 中使用了这个

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

你会有点击处理程序.. 所以在 Typescript 中添加

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

【讨论】:

  • 感谢您的回答,slideToogle() 是一个 jquery 函数,我尝试按照您所说的方式进行操作,但在 this.h2El.slideToggle(); 上出现错误,它说 [ts] Property 'slideToggle' does not exist on type 'Element'.. 好像我不能在上使用 jquery像这样的元素..
  • @Zekelonas 我认为$(event.target).slideToggle(); 会更合适。但是如果你根本不能使用 Jquery,那么这没关系......
  • 元素是一个接口。存在具有不同特异性水平的接口。这里有一个更完整的列表:developer.mozilla.org/en-US/docs/Web/API 例如,HTMLDivElement。在 Typescript 中,您可以使用以下任一语法转换变量: elDiv as HTMLDivElement 或 elDiv 有时这使您能够调用方法。但我怀疑 JQuery 正在美化底层接口原型以添加 slideToggle()。所以你可能在代码中的某个时候仍然需要 jQuery。
【解决方案2】:

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

依赖视图元素的操作最早需要在ngAfterViewInit lifecycle hook中执行

export class HomeComponent implements OnInit, OnAfterViewInit 
...

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

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

【讨论】:

  • 我的朋友 uoooww 非常感谢您解决我的问题
【解决方案3】:

按照对我有用的步骤:

安装 jquery npm 安装 jquery

安装ts类型 npm install @types/jquery

在你的 .angular-cli.json 中添加 jquery.min.js:

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

使用 Token、Provider 和 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 };

在模块中添加提供者:

@NgModule({
  declarations: [
    ...
  ],
  providers: [
    JQUERY_PROVIDER,
    ...
  ]
})

在任何组件中使用 DI:

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

要开心:D

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

【讨论】:

    【解决方案4】:

    Easiest and Shortest way possible to use jQuery in Angular 2/4

    第一步

    来自 index.html

    我的测试项目\src\index.html

    app-root标签下方输入jQuery cdn。

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

    第二步

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

    转到所需的组件 .ts 脚本。

    import { Component, OnInit } from '@angular/core';
    
    // this line will allow you to use jQuery
    declare var $: any;
    
    @Component({
      ...
    })
    

    第三步

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

    通过在 jQuery 语法 $(() =&gt; { /* content here */ }) 中记录 'I&lt;3Cats' 来测试 jQuery。

    export class TestComponent implements OnInit {
    
      constructor() { }
    
      ngOnInit() {
        $(() => {
          console.log('hello there!');
        });
      }
    
    }
    

    您也可以将此技术与其他 javscript 库一起使用。我不知道这是否安全,但肯定会帮助你。相当

    【讨论】:

      【解决方案5】:

      你的 onInit 方法在构造函数里面,试试下面的方法

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

      【讨论】:

      • 请编辑您的答案并为您的代码添加一些解释。不鼓励仅使用代码的答案,可能会被删除。
      【解决方案6】:

      我遇到了 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');
          // });
        }
      
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-06-17
        • 2018-03-24
        • 1970-01-01
        • 1970-01-01
        • 2018-10-19
        • 2018-04-12
        相关资源
        最近更新 更多