首页 > 解决方案 > 我正在尝试将 Jquery Combo-Tree 插件集成到 Angular 6 应用程序中

问题描述

我正面临这个错误。“错误:$(...).comboTree 不是函数”

我已经安装了 jquery,@types/jquery。
添加 comboTree.js 插件和 icontainer.js。

Stackblitz 网址:

https://stackblitz.com/edit/angular-pg3hjd

这是我的代码

app.component.ts

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

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  name = 'Angular';

    ngOnInit() {
// SampleJSONData Be the Json with tree structure

var comboTree1, comboTree2;

$(document).ready(function($) {
	
 comboTree2 = $('#justAnotherInputBox').comboTree({
			source : SampleJSONData,
			isMultiple: false
		});
});
  }
}
<div class="row">
		<div class="col-lg-6">
			<h3>Single Selection</h3>
			<input type="text" id="justAnotherInputBox" placeholder="Type to filter"/>
		</div>

	</div>

标签: jquery-pluginsangular6

解决方案


comboTree 是一个 jQuery 插件。你也需要安装它。从他们的github下载 comboTreePlugin.js并将其添加到您的项目中。然后你的 app.component.ts 在导入 jquery 后导入它。

import { Component, OnInit } from '@angular/core';
import  $ from 'jquery';
import '../comboTreePlugin';  // enter proper path here, depending where you saved the plugin in your project.

... rest of your code ...

现在打开 comboTreePlugin.js 并在那里导入 jquery:

import jQuery from 'jquery';


但是编辑供应商包以在其中导入 jquery 不是您应该做的事情。解决这个问题的更优雅的方法是:

  1. 创建一个名为“globals.js”的文件(或任何你想命名的文件)
  2. 在其中写下:

    import jquery from 'jquery';
    
    window.$ = jquery;
    window.jQuery = jquery;
    
  3. 现在在您的 app.component.ts 中,您的导入应该如下所示:

    import { Component,OnInit } from '@angular/core';
    import './globals';
    import '../comboTreePlugin';
    
    ... rest of your code ...
    
  4. 它现在应该可以工作了,无需在 comboTreePlugin.js 中编辑任何内容

    现在无需在您的组件中导入 jquery,因为导入全局变量将同时引入$jQuery引入范围。

Stackblitz:
https ://stackblitz.com/edit/angular-qswozq
https://angular-qswozq.stackblitz.io


推荐阅读