angulartooltipbootstrap-4tether

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!


Solution

  • 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!