如何使用 jquery 在 angular 7 中使用 bootstrap popover?

Ash*_*ini 1 jquery popover bootstrap-4 angular7

我正在尝试在 angular7 中使用 jquery 实现 bootstrap4 popover。我在 index.html 中包含了“popper.js”,也使用 npm 包含了。但它不起作用。

未捕获的类型错误:jquery__WEBPACK_IMPORTED_MODULE_2__(...).popover 不是函数

此错误仅出现在控制台中。

HTML:(sample.component.html)

<button id="option2" autocomplete="off" data-toggle="popover"> Public</button>
Run Code Online (Sandbox Code Playgroud)

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'
      });            
    });
  }
Run Code Online (Sandbox Code Playgroud)

如何在 angular 7 中实现 bootstrap popover?

小智 5

将您的组件文件更改为这种方式:

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();
  }
Run Code Online (Sandbox Code Playgroud)

你不需要使用$(document).ready()因为NgOnInit()做同样的事情。并且$('[data-toggle="popover"]').popover();将启动您组件中的所有 Popover。

您可以使用 title、data-placement 和 data-content 属性来制作 Popover,例如:

<button id="option2" autocomplete="off" data-toggle="popover" data-placement="bottom" title="popover's title" data-content="popover's text"> Public</button>
Run Code Online (Sandbox Code Playgroud)

或者您可以使用您在中使用的函数初始化弹出窗口NgOnInit()

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

希望这可以帮助。

  • 请不要在 Angular 中使用 jQuery :( :( (3认同)