3

I'm trying to use Bootstrap4 tooltips in an Angular app built using the Angular CLI.

The Bootstrap4 alpha documentation says that I need to run this command in order to enable tooltips:

$(function () {
    $('[data-toggle="tooltip"]').tooltip()
})

So, I've added a ngAfterViewInit() function in the app.component.ts to do that:

ngAfterViewInit() {
    $('[data-toggle="tooltip"]').tooltip();
}

With this in the app html file:

<button type="button" class="btn btn-secondary" data-toggle="tooltip" data-placement="top" title="Hi there!">
    Tooltip Test
</button>

I do see a tooltip when hovering over the button, but it is just a normal browser tooltip, not a Bootstrap4 tooltip.

At run time, I get the error:

ERROR ReferenceError: $ is not defined

Adding this line to the component does not help.

declare var $: any;

I've double-checked that the jquery, tether, and boostrap js files are included in that order in the scripts section of the project angular-cli.json file.

Any suggestions how I might get this to work?

Thanks!

Zze
  • 18,229
  • 13
  • 85
  • 118
  • did u try placing an `id` and use `getElementById` instead of that `$('[data-toggle="tooltip"]')` ? – DrNio Dec 03 '17 at 21:35
  • My suggestion: use ng-bootstrap [Tooltip component](https://ng-bootstrap.github.io/#/components/tooltip/examples). – ConnorsFan Dec 03 '17 at 22:23

2 Answers2

11

You need to install jquery and bootstrap typings to make them available in Typescript and Angular.

For bootstrap npm install --save @types/bootstrap For jquery npm install --save @types/jquery

Import bootstrap as shown: import 'bootstrap'

Import jquery this way import * as $ from 'jquery'

Make sure to initialize bootstrap tooltip in ngAfterViewChecked `

import 'bootstrap';
import * as $ from 'jquery';
//extras removed for brevity
export class MyComponent implements AfterViewChecked {
  ngAfterViewChecked() {
     $('[data-toggle="tooltip"]').tooltip();
  }
}

`

Hope this helps!

0

We implemented Chinemere Okereke's solution (Thank you) and ran into the following error at runtime :

ERROR Error: TOOLTIP: Option "sanitizeFn" provided type "window" but expected type "null|function)"

And had to add the sanitize: and sanitizeFn: to the .tooltip() call :

ngAfterViewChecked() {
    const $ = $_;
    $('[data-toggle="tooltip"]').tooltip({sanitize: false, sanitizeFn: content => content});
}

Working great! hope this helps

lincolnadym
  • 909
  • 1
  • 12
  • 29