我试图在一个新的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识别它?
发布于 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
希望这能有所帮助!
https://stackoverflow.com/questions/49805573
复制相似问题