【问题标题】:How to use bootstrap component which extends jQuery in angular?如何使用以角度扩展 jQuery 的引导组件?
【发布时间】:2018-08-16 05:01:03
【问题描述】:

我正在尝试在新的 angular 4 应用中使用 bootstrap 3.3.7 弹出框组件(我不能使用 ng 版本),所以我已经安装了:

npm install --save jquery @types/jquery bootstrap

然后我将 css 和脚本添加到 angular-cli.json

 "styles": [
    "../node_modules/bootstrap/dist/css/bootstrap.css",
    "../node_modules/bootstrap-tour/build/css/bootstrap-tour.css",
    "styles.css"
  ],
  "scripts": [
    "../node_modules/jquery/dist/jquery.js",
    "../node_modules/bootstrap/dist/js/bootstrap.js",
    "../node_modules/bootstrap-tour/build/js/bootstrap-tour.js"
  ]

然后在typings.d.ts文件中我添加了一个接口:

interface Jquery { 
   popover(...any) : any;
}

然后在我的组件中我导入了 jQuery:

import * as $ from "jquery"

但是当我尝试执行 popover 方法时出现编译错误:

('#test1').popover('show'); //here i have a compilation error on the popover method.

如何让打字稿识别?

【问题讨论】:

  • npm install --save jquery @types/jquery bootstrap - 很明显也安装了@types/bootstrap。你试过了吗?

标签: angular typescript


【解决方案1】:

这是我如何在使用 cli 创建的新 Angular 项目上使用它的方法:

npm install --save jquery bootstrap@3.3.7

app.component.ts 更新为:

import { AfterViewInit, Component, ElementRef, ViewChild } from '@angular/core';

declare const $: any;

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements AfterViewInit {
  @ViewChild('div') divElement: ElementRef;

  ngAfterViewInit(): void {
    $(this.divElement.nativeElement).popover({content: 'foobar', placement: 'bottom'}).popover('show');
  }
}

app.component.html

<div #div>hello there</div>

由于angular-cli.json 中添加的脚本和样式将这些文件添加到全局范围,因此按照您的方式进行导入只会使事情变得混乱。这将导致 jQuery 被第二次导入,这次是在引导脚本之后。

一般来说,最好尝试以您拥有它们的方式进行导入,因为这将允许 typescript/webpack 加载所需的脚本并执行其他一些构建时间魔法。由于版本 3 中的引导脚本依赖于 jQuery,全局作用域脚本方法似乎是必需的。

为了避免打字稿抱怨,你需要告诉它全局 jQuery 对象,这通过 declare const $: any; 行完成

完整的 GitHub 代码库here

希望这会有所帮助!

【讨论】:

    猜你喜欢
    • 2013-05-23
    • 2021-09-03
    • 1970-01-01
    • 1970-01-01
    • 2018-08-24
    • 2016-11-13
    • 2017-04-12
    • 2019-05-22
    • 2017-05-08
    相关资源
    最近更新 更多