首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何在angular中使用扩展jQuery的bootstrap组件?

如何在angular中使用扩展jQuery的bootstrap组件?
EN

Stack Overflow用户
提问于 2018-04-13 04:45:38
回答 1查看 379关注 0票数 0

我试图在一个新的angular 4应用程序中使用bootstrap 3.3.7 popover组件(我不能使用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.

如何让typescript识别它?

EN

回答 1

Stack Overflow用户

发布于 2018-08-16 05:01:04

下面是我如何在使用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的方式,全局范围脚本方法似乎是必需的。

但是,为了防止typescript出现错误,您需要告诉它有关全局jQuery对象的信息,这是通过declare const $: any;行完成的

完整的GitHub存储库here

希望这能有所帮助!

票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/49805573

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档