在angular4的項目中須要使用bootstrap的tooltip插件。javascript
1. 使用命令安裝jQuery和bootstrapcss
npm install bootstrap jquery --save
2. 安裝了bootstrap和jQuery以後,須要在.angular-cli.json中設置對jQuery和bootstrap的引用。html
... "styles": [ "styles/bootstrap.scss", "styles.scss", ], "scripts": [ "../node_modules/jquery/dist/jquery.js", "../node_modules/jqueryui/jquery-ui.js", "../node_modules/bootstrap/dist/js/bootstrap.js", ] ...
3. 使用directive來定義一個可共用的屬性指令。java
import { AfterViewInit, Directive, ElementRef, HostBinding, Input, OnDestroy } from '@angular/core'; /** * @see https://getbootstrap.com/docs/3.3/javascript/#tooltips */ @Directive({ selector: '[appTooltip]' }) export class TooltipDirective implements AfterViewInit, OnDestroy { // @HostBinding('attr.data-toggle') // readonly dataToggle = 'tooltip'; @Input() @HostBinding('attr.data-placement') appTooltipPlacement = 'bottom'; @Input() @HostBinding('title') appTooltip: string; constructor(private elementRef: ElementRef) { } ngAfterViewInit(): void { // bugfix: 使用 container: 'body' 能夠避免在 btn-group 時因爲插入了 tooltip 後, // 最後一個 button 不知足 :not(:last-child) 時致使的圓角消失的 bug $(this.elementRef.nativeElement).tooltip({ container: 'body' } as any); } ngOnDestroy(): void { $(this.elementRef.nativeElement).tooltip('destroy'); } }
4. 在app.module.ts中聲明這個directive,須要在declarations和exports中引入node
... import {TooltipDirective} from './common/directives/tooltip.directive'; @NgModule({ declarations: [ AppComponent, ... TooltipDirective ], imports: [ BrowserModule, FormsModule, ... ], exports: [TooltipDirective], entryComponents: [ .... ], providers: [...], bootstrap: [AppComponent] }) export class AppModule { constructor() { ... } }
5.html頁面裏面使用[appTooltip] 來使用這個directive。jquery
<button type="button" class="btn btn-default" (click)="new.emit()" appTooltip="新建"> <i class="i-new"></i> </button>
5. 不過這裏出現一個報錯。npm
Property 'tooltip' does no t exist on type 'JQuery<HTMLElement>
檢查了好久,後來找到了問題,沒有聲明$。json
須要在tooltip.directive.ts文件中加上bootstrap
declare let $: any;
,而後就能夠正常使用了。app
6.要在項目內全局設置jQuery的引用,在tsconfig.json文件中配置紅色顯示的部分
{ "compileOnSave": true, "compilerOptions": { "outDir": "./dist/out-tsc", "sourceMap": true, "declaration": false, "moduleResolution": "node", "emitDecoratorMetadata": true, "experimentalDecorators": true, "skipLibCheck": true, "strictNullChecks": false, "noStrictGenericChecks": false, "target": "es5", "typeRoots": [ "node_modules/@types" ], "types": [ "jasmine", "node", "jquery", "jqueryui" ], "lib": [ "es2017", "dom" ] } }