Search code examples
jquerybootstrap-4angular7popover

How to use bootstrap popover in angular 7 using jquery?


I am trying to implement bootstrap4 popover using jquery in angular7. I have included "popper.js" in index.html and included using npm too. but it's not working.

Uncaught TypeError: jquery__WEBPACK_IMPORTED_MODULE_2__(...).popover is not a function

this error only appears in the console.

HTML:(sample.component.html)

<button id="option2" autocomplete="off" data-toggle="popover"> Public</button>

Jquery: (sample.component.ts)

import { Component, OnInit } from '@angular/core';
import * as $ from 'jquery';

@Component({
  selector: 'app-sample',
  templateUrl: './sample.component.html',
  styleUrls: ['./sample.component.css']
})
export class SampleComponent implements OnInit {

  constructor() { }   
  ngOnInit() {   
    $(document).ready(function(){   
      $('[data-toggle="popover"]').popover();     
      $('#option2').popover({
         html: true,
        content: function() {
          return $("#div").html();
        },
         placement: 'bottom'
      });            
    });
  }

How to achieve bootstrap popover in angular 7?


Solution

  • Attention: using jQuery in Angular is not a good practice as @ErikHer implied. The interesting thing in this case is to use the ng-bootstrap library, which is a library developed in the angular standards with the elements Bootstrap 4 or less. Also you can use Bootstrap 5, where they stopped using jQuery.

    Anyway, the method below works, but it is not recommended.

    Thank you @ErikHer for making the answer more complete.


    Change your component file to that way:

    import { Component, OnInit } from '@angular/core';
    declare var $: any; // ADD THIS
    import * as $ from 'jquery';
    
    @Component({
      selector: 'app-sample',
      templateUrl: './sample.component.html',
      styleUrls: ['./sample.component.css']
    })
    export class SampleComponent implements OnInit {
    
      constructor() { }   
      ngOnInit() {   
        $('[data-toggle="popover"]').popover();
      }
    

    You don't need use $(document).ready() because the NgOnInit() do the same thing. And the $('[data-toggle="popover"]').popover(); will start all Popover you have in your component.

    You can use title, data-placement and data-content attributes for make the Popover like:

    <button id="option2" autocomplete="off" data-toggle="popover" data-placement="bottom" title="popover's title" data-content="popover's text"> Public</button>
    

    Or you can initialize the popover with the function that you used in NgOnInit():

    $('#option2').popover({
             html: true,
            content: function() {
              return $("#div").html();
            },
             placement: 'bottom'
          }); 
    

    Hope this helps.