javascript - 将 jQuery 插件与 Angular 5 (Typescript) 一起使用失败

标签 javascript jquery angular typescript

我正在尝试集成这个插件:https://github.com/gridstack/gridstack.js进入一个新的 Angular 5 (Typescript) 应用程序,但我遇到了这个错误:

enter image description here

我已经使用以下方法安装了这个 jQuery 库:npm install gridstack

这是我的代码:

应用程序组件.ts

import { Component, OnInit } from '@angular/core';

import * as $ from 'jquery';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

export class AppComponent implements OnInit {
  title = 'app';

    constructor() {}

  ngOnInit() {
    $(document).ready(function(){
      // It works.
      $("button").click(function(){
        var div = $("div");
        div.animate({left: '100px'}, "slow");
        div.animate({fontSize: '5em'}, "slow");
      });

      // Failed !!!
      $('.grid-stack').gridstack();

    });
  }
}

app.component.html

<div style="text-align:center">
  <h1>
    Hello World!
  </h1>

  <button>Start Animation</button>
  <div style="border:1px solid #555;border-radius:3px;color:white;background:#555;height:105px;width:260px;position:relative; margin-top:10px">jQuery</div>

<div class="grid-stack">
    <div class="grid-stack-item"
        data-gs-x="0" data-gs-y="0"
        data-gs-width="4" data-gs-height="2">
            <div class="grid-stack-item-content"></div>
    </div>
    <div class="grid-stack-item"
        data-gs-x="4" data-gs-y="0"
        data-gs-width="4" data-gs-height="4">
            <div class="grid-stack-item-content"></div>
    </div>
</div>


</div>

显示错误的演示:https://stackblitz.com/edit/angular-1sidhl

最佳答案

在下面尝试。

在你的组件中。

    declare var $el: JQuery;  // This is missing in your code, you have to declare $ as variable.

    @Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
     })
   export class AppComponent implements OnInit {

       ngOnInit() {
    $(document).ready(function(){

这应该有效。

关于javascript - 将 jQuery 插件与 Angular 5 (Typescript) 一起使用失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49611038/

相关文章:

angular - 我怎样才能把这个对象以 Angular 形式放入 Material 表中

javascript - 如何在 Angular 2 上调用 javascript

javascript - JS 一直有效,直到我将它带入基础框架

javascript - 在偶数监听器 block 中绑定(bind)和解除绑定(bind)

javascript - JQuery 脚本循环错误

javascript - Google "reCaptcha"有时无法显示/呈现

JavaScript JQuery 隐藏/显示功能

javascript - 如何使用 Jquery 删除文本区域的第一行?

javascript - 将变量从复选框传递给 onclick 函数

javascript - ionic Angular : Triggering checkbox from card click