我正在尝试将此插件:https://github.com/gridstack/gridstack.js集成到新的Angular 5(Typescript)应用程序中,但是我遇到此错误:

javascript - 将jQuery插件与Angular 5(Typescript)结合使用失败-LMLPHP

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

这是我的代码:

app.component.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(){


这应该工作。

07-24 17:12