Search code examples
angulartwitter-bootstraptooltipbootstrap-5

Bootstrap 5 tooltip not working in Angular 11 project


I try to use Bootstrap 5.0.2 in an Angular 11 project with this code:

index.html

<!doctype html>
<html lang="en">

<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1"/>
  <meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate">
  <meta http-equiv="Pragma" content="no-cache">
  <meta http-equiv="Expires" content="0">
  <title>My Project</title>
  <base href="/">
  <meta http-equiv="content-language" content="en-US" />

  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
  <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.9.2/dist/umd/popper.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>
</head>
<body>
  <app-root></app-root>
</body>
</html>

In a component:

<a class="btn btn-primary"
  data-bs-toggle="tooltip"
  data-bs-html="true"
  data-bs-placement="top"
  [title]="myTitle | toHtmlEntity"
  [href]="myUrl">

  {{ myButtonLabel }}
</a>

No error message, but the tooltip is not working. The title string showed up when the mouse hover the link.

Any idea what I missed?


Solution

  • To add on @yatinsingla's answer, don't forget to add

    declare var bootstrap: any
    

    at the top of your component class, just below the imports.

    So you have:

    import {} from "....";
    ....
    declare var bootstrap: any;
    
    export class YourComponent implements OnInit, <other interfaces> {       
        ngOnInit(): void {
            // Bootstrap tooltip initialization
            var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'))
            var tooltipList = tooltipTriggerList.map(function (tooltipTriggerEl) {
            return new bootstrap.Tooltip(tooltipTriggerEl)
            })       
        }
    }
    

    If you need to initizalize bootstrap 5's popovers, add the javascript initialization code (just copy it from the bootstrap's docs) in the ngOnInit() function the same was as for the tooltips.