使用Angular 2使用Typeahead.js



我试图使用带有Angular 2的Typeahead.js(使用Blood Hound功能,因为它是最好的功能(。但是,我遇到了将JS文件导入项目的困难。

我在index.html中具有以下内容:

<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

和打字文件:

<script src="https://cdnjs.cloudflare.com/ajax/libs/typeahead.js/0.11.1/typeahead.bundle.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/corejs-typeahead/1.1.1/bloodhound.min.js"></script>

我还将jQuery导入如下所示:

..
map: {
      'jquery': 'https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js',
}..

我在ngafterviewinit方法中有jQuery:

ngAfterViewInit() {
            console.log("jQuery is ready");
            // constructs the suggestion engine
            var states = new Bloodhound({
                datumTokenizer: Bloodhound.tokenizers.whitespace,
                queryTokenizer: Bloodhound.tokenizers.whitespace,
                // `states` is an array of state names defined in "The Basics"
                local: states
            });
            $('#bloodhound .typeahead').typeahead({
                hint: true,
                highlight: true,
                minLength: 1
            },
                {
                    name: 'states',
                    source: states
            });


    }

jQuery作品(由控制台日志条目确认(。但是我会收到以下错误:

jquery.deferred例外:$(...(。打字不是函数 TypeError:$(...(。打字不是函数

错误类型:$(...(。打字不是函数

这是我的解决方案。希望有人可以帮助这一点。

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

npm install --save @types/typeahead

也将以下文件添加到Angular-cli.json文件。

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

在组件的OnInit((方法中do the of 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
  });

我也安装了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>

最新更新