在angular项目中使用bootstrap的tooltip插件时,报错Property 'tooltip' does no t exist on type 'JQuery的解决方法和过程

在angular4的项目中需要使用bootstrap的tooltip插件。

1. 使用命令安装jQuery和bootstrap

npm install bootstrap jquery --save

2. 安装了bootstrap和jQuery之后,需要在.angular-cli.json中设置对jQuery和bootstrap的引用。

...
    "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来定义一个可共用的属性指令。

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中引入

...
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。

<button type="button" class="btn btn-default" (click)="new.emit()" appTooltip="新建">
            <i class="i-new"></i>
</button>

5. 不过这里出现一个报错。

Property 'tooltip' does no t exist on type 'JQuery<HTMLElement>

检查了很久,后来找到了问题,没有声明$。

需要在tooltip.directive.ts文件中加上

declare let $: any;

,然后就可以正常使用了。

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"
    ]
  }
}