user1134725
user1134725

Reputation:

How to enable Bootstrap4 tooltips inside an Angular app

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!

Upvotes: 3

Views: 4437

Answers (2)

lincolnadym
lincolnadym

Reputation: 1000

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

Upvotes: 0

Chinemere Okereke
Chinemere Okereke

Reputation: 321

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!

Upvotes: 12

Related Questions