简体   繁体   English

将Bloodhound导入Angular 2 CLI项目

[英]Importing Bloodhound into Angular 2 CLI project

I am trying to implement Bloodhound.js into an Angular 2 project that is using Angular 2 CLI. 我正在尝试将Bloodhound.js实现到使用Angular 2 CLI的Angular 2项目中。 At the moment I have jQuery working through the following methods: 目前我让jQuery通过以下方法工作:

  1. npm install jquery --save npm install jquery --save

  2. npm install @types/jquery --save-dev npm install @ types / jquery --save-dev

  3. Then adding '"../node_modules/jquery/dist/jquery.min.js"' to the scripts array in the angular-cli.json. 然后将'“../node_modules/jquery/dist/jquery.min.js”添加到angular-cli.json中的scripts数组中。

I have done the same for Bloodhound.js in the angular-cli.json as well with the following: 我对angular-cli.json中的Bloodhound.js做了同样的事情,并且如下:

"../node_modules/bloodhound-js/dist/bloodhound.min.js" “../node_modules/bloodhound-js/dist/bloodhound.min.js”

However I get the following error: 但是我收到以下错误:

Cannot find name 'Bloodhound'. 找不到名字'Bloodhound'。

Is there a way to import the .js file directly or to add the import locally? 有没有办法直接导入.js文件或在本地添加导入?

Here is the my solution. 这是我的解决方案。 Hope someone can help this. 希望有人可以帮助这个。

Install typehead.js type definition using following command. 使用以下命令安装typehead.js类型定义。

npm install --save @types/typeahead

Add following files to angular-cli.json file too. 将以下文件添加到angular-cli.json文件中。

"assets/js/bloodhound.min.js",
"assets/js/typeahead.bundle.min.js"

Do following in OnInit() method of the component 在组件的OnInit()方法中执行以下操作

const suggestions = [{
          value: 'string1'
        }, {
          value: 'string2'
        }, {
          value: 'string3'
        }, {
          value: 'string4'
        }, {
          value: 'string5'
        }];

 let bloodhoundSuggestions = new Bloodhound({
        datumTokenizer: Bloodhound.tokenizers.obj.whitespace('value'),
        queryTokenizer: Bloodhound.tokenizers.whitespace,
        sufficient: 3,
        local: this.suggestions
 });

 $('#tagsInput .typeahead').typeahead({
      hint: true,
      highlight: true,
      minLength: 1
    }, {
        name: 'suggestions',
        displayKey: 'value',
        source: bloodhoundSuggestions
  });

I have installed jQuery too. 我也安装了jQuery。

Please make sure to add following to app.component.ts 请务必在app.component.ts中添加以下内容

import * as $ from 'jquery';

And Make sure to import following on your component file. 并确保在组件文件中导入以下内容。

declare const Bloodhound;
declare const $;

Component Html File 组件Html文件

<div id="tagsInput">
   <input class="typeahead" type="text" placeholder="States of USA">
</div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM