Importing Bloodhound into Angular 2 CLI project

Viewed 566

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?

1 Answers

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>
Related