網站搜尋

angular - 屬性 'modal' 不存在於類型 'JQuery' 上 Angular6


當我在 TypeScript Angular6 中使用 jQuery 時出現以下錯誤,請幫助我

jQuery('#assignsp').modal('show');

遵循這些步驟

3 步驟:

安裝 jQuery。(如果已安裝,請跳過)

npm install jquery --save 安裝 jQuery 的型別定義。

npm 安裝 @types/jquery --save

Import jQuery in app.module.ts.

import * as $ from 'jquery';

它顯示我錯誤

錯誤 TS2339:屬性 'modal' 不存在於類型 'JQuery<HTMLElement>'

錯誤 TS2339:屬性 'modal' 不存在於類型 'JQuery' 上。

答案#1

你同時嘗試做多件事。首先,你需要將 jQuery 與 TypeScript 整合,其次,要整合 Bootstrap 的模態框功能,而這最終依賴於 jQuery。讓我們先整合 jQuery,然後再進行 Bootstrap 的整合。

jQuery 安裝:你已經在這裡做了很多事情

npm install jquery --save

npm install @types/jquery --save

npm i bootstrap --save

Angular 配置:在此處添加 jQuery 和 Bootstrap 的條目:

"styles":[
           "src/styles.css",
            "./node_modules/bootstrap/dist/css/bootstrap.min.css"
         ],
"scripts":[
            "./node_modules/jquery/dist/jquery.min.js",
             "./node_modules/bootstrap/dist/js/bootstrap.min.js"
           ]

Typescript 配置:在你的組件頂部添加這些行。

/// <reference path ="../../node_modules/@types/jquery/index.d.ts"/>
declare var $: any 
ngOnInit() {
    $('#myModal').modal('show');
}

HTML:在此處添加模態代碼

<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
        <h4 class="modal-title" id="exampleModalLabel">Modal</h4>
      </div>
      <div class="modal-body">
        Modal content
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
      </div>
    </div>
  </div>
</div>

我已經嘗試了上述方法,它對我有效。如果你仍然遇到錯誤,請告訴我。

答案#2

    import * as $AB from 'jquery';
        jQuery('#exampleModal').show();
   jQuery('#exampleModal').hide();