有人能告诉我,如何在Angular中使用jQuery吗?

class MyComponent {
    constructor() {
        // how to query the DOM element from here?
    }
}

我知道有一些变通办法,比如在前面操纵DOM元素的类或id,但我希望有一种更干净的方式来做到这一点。


当前回答

第一步:使用命令:NPM install jquery——save

步骤2:你可以简单地导入angular:

从jquery中导入$;

就这些。

一个例子是:

import { Component } from '@angular/core';
import  $ from 'jquery';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

export class AppComponent {
  title = 'app';
  constructor(){
    console.log($('body'));
  }


}

其他回答

为什么每个人都把它搞得很复杂? 对于任何需要在静态元素上做一些基本的事情的人,例如,body标签,只需这样做:

在index.html中添加带有你的jquery库路径的script标签,不管在哪里(这样你也可以使用IE条件标签来加载IE9或更低版本的jquery)。 在导出组件块中有一个调用代码的函数:$("body").addClass("done");通常这会导致声明错误,所以在.ts文件中的所有导入之后,添加declare var $:any;你就可以开始了!

第一步:使用命令:NPM install jquery——save

步骤2:你可以简单地导入angular:

从jquery中导入$;

就这些。

一个例子是:

import { Component } from '@angular/core';
import  $ from 'jquery';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

export class AppComponent {
  title = 'app';
  constructor(){
    console.log($('body'));
  }


}

现在它变得非常简单,你可以通过在Angular2控制器中声明任意类型的jQuery变量来实现。

declare var jQuery:any;

将其添加在import语句之后和组件装饰符之前。

要访问任何id为X或类为X的元素,你只需要这样做

jQuery("#X or .X").someFunc();

因为我是一个笨蛋,我认为有一些工作代码会很好。

此外,Angular2类型版本的角量角器与jQuery $有问题,所以顶部接受的答案没有给我一个干净的编译。

以下是我开始工作的步骤:

index . html

<head>
...
    <script   src="https://code.jquery.com/jquery-3.1.1.min.js"   integrity="sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8="   crossorigin="anonymous"></script>
...
</head>

内部my.component.ts

import {
    Component,
    EventEmitter,
    Input,
    OnInit,
    Output,
    NgZone,
    AfterContentChecked,
    ElementRef,
    ViewChild
} from "@angular/core";
import {Router} from "@angular/router";

declare var jQuery:any;

@Component({
    moduleId: module.id,
    selector: 'mycomponent',
    templateUrl: 'my.component.html',
    styleUrls: ['../../scss/my.component.css'],
})
export class MyComponent implements OnInit, AfterContentChecked{
...
    scrollLeft() {

        jQuery('#myElement').animate({scrollLeft: 100}, 500);

    }
}

一个简单的方法:

1. 包括脚本

index . html

<script type="text/javascript" src="assets/js/jquery-2.1.1.min.js"></script>

2. 声明

my.component.ts

declare var $: any;

3.使用

@Component({
  selector: 'home',
  templateUrl: './my.component.html',
})
export class MyComponent implements OnInit {
 ...
  $("#myselector").style="display: none;";
}