Bootstrap 在 Angular 7 上出现错误,因为 '属性 崩溃在类型 `JQuery<HTMLElement>` 上不存在

Bootstrap on Angular 7 getting error as 'Property collapse does not exist on type `JQuery<HTMLElement>`

我试图通过在下拉菜单外单击来关闭 collapse 面板。我尝试使用以下代码:

import { Component, OnInit } from '@angular/core';
import { Store, select } from '@ngrx/store';
declare var $:JQueryStatic;
import { State } from "./../../state/app.state";
import * as fromSetupConfig from "./../../setup-config/state/setup-config.reducer";

@Component({
    selector: 'app-header',
    templateUrl: './header.component.html',
    styleUrls: ['./header.component.scss']
})
export class HeaderComponent implements OnInit {

    constructor(private store:Store<State>) { }

    currentName:string;

    ngOnInit() {

        this.store.pipe(select(fromSetupConfig.getCurrentName)).subscribe(newName => {
            this.currentName = newName
        });

        $(document).click(function(e) {
            if (!$(e.target).is('.panel-body')) {
                $('.collapse').collapse('hide');      //throws error  
            }
        });

    }

}

但是出现错误:Property collapse does not exist on typeJQuery` - 如何解决这个问题?

您在这里遇到的问题是因为打字稿编译器。为避免这种情况,您可以在基本 JS 文件中初始化折叠和其他元素。您将需要导入此文件,以便在资产文件夹中创建它(并且 link 在您的 index.html 中)或在其他位置创建它,并在 scripts 部分提及它 angular.json

要初始化崩溃,此 JS 文件的内容为:

$(document).click(function(e) {
    if (!$(e.target).is('.panel-body')) {
        $('.collapse').collapse('hide');      //throws error  
    }
});

当文档准备就绪时,这将初始化所有 Jquery 函数。

如果您想在 Angular 流程中的特定时刻执行此操作,请将调用包装在函数中,如下所示:

function collapse() {
  $(document).click(function(e) {
    if (!$(e.target).is('.panel-body')) {
        $('.collapse').collapse('hide');      //throws error  
    }
  });
}

要在 Typescript 文件中调用它,您需要先声明该函数。例如,要初始化 ngOnInit() 中的 jquery 函数:

declare function collapse();
ngOnInit() {
  collapse();
}

这样你就不需要在任何地方import 'bootstrap';,所以你不会破坏你的其他组件。

对于任何不想要这种类型修复的人,最简单的方法是通过 运行 npm install @types/bootstrap 安装 @types/bootstrap 包,然后使用 bootstrap 导入 bootstrap import 'bootstrap'。这至少对我有帮助,而且在打字稿之外添加一个函数并在之后告诉打字稿,它也更清晰,有这样一个函数,它只需要相信我。

此外,declare var $:JQueryStatic 只是一种告诉打字稿相信我的方式,而不是实际检查它是否为真,即 $ 是 JQuery,这里干净的方式类似于 import * as $ from 'jquery';.

Greatings DragonSkills99