简体   繁体   中英

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. At the moment I have jQuery working through the following methods:

  1. npm install jquery --save

  2. 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.

I have done the same for Bloodhound.js in the angular-cli.json as well with the following:

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

However I get the following error:

Cannot find name 'Bloodhound'.

Is there a way to import the .js file directly or to add the import locally?

Here is the my solution. Hope someone can help this.

Install typehead.js type definition using following command.

npm install --save @types/typeahead

Add following files to angular-cli.json file too.

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

Do following in OnInit() method of the component

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.

Please make sure to add following to 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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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