首页 文章

将Bloodhound导入Angular 2 CLI项目

提问于
浏览
2

我正在尝试将Bloodhound.js实现到使用Angular 2 CLI的Angular 2项目中 . 目前我让jQuery通过以下方法工作:

  • npm install jquery --save

  • npm install @ types / jquery --save-dev

  • 然后将'“../ node_modules/jquery/dist/jquery.min.js”添加到angular-cli.json中的scripts数组中 .

我对angular-cli.json中的Bloodhound.js做了同样的事情,并且如下:

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

但是我收到以下错误:

找不到名字'Bloodhound' .

有没有办法直接导入.js文件或在本地添加导入?

1 回答

  • 1

    这是我的解决方案 . 希望有人可以帮助这个 .

    使用以下命令安装typehead.js类型定义 .

    npm install --save @types/typeahead
    

    将以下文件添加到angular-cli.json文件中 .

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

    在组件的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
      });
    

    我也安装了jQuery .

    请务必在app.component.ts中添加以下内容

    import * as $ from 'jquery';
    

    并确保在组件文件中导入以下内容 .

    declare const Bloodhound;
    declare const $;
    

    组件Html文件

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

相关问题