Bootstrap 5 工具提示在 Angular 11 项目中不起作用

问题描述 投票:0回答:7

我尝试在 Angular 11 项目中使用 Bootstrap 5.0.2 并使用以下代码:

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/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
  <script src="https://cdn.jsdelivr.net/npm/@popperjs/[email protected]/dist/umd/popper.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>
</head>
<body>
  <app-root></app-root>
</body>
</html>

在组件中:

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

  {{ myButtonLabel }}
</a>

没有错误消息,但工具提示不起作用。当鼠标悬停在链接上时会显示标题字符串。

知道我错过了什么吗?

angular twitter-bootstrap tooltip bootstrap-5
7个回答
9
投票

要添加@yatinsingla的答案,请不要忘记添加

declare var bootstrap: any

在组件类的顶部,就在导入的下方。

所以你有:

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)
        })       
    }
}

如果您需要初始化 bootstrap 5 的 popovers,请在 ngOnInit() 函数中添加 javascript 初始化代码(只需从引导程序的文档中复制它),与工具提示相同。


1
投票

package.json

"@popperjs/core": "^2.10.2",    
"bootstrap": "^5.1.3",

角度.json

 "scripts": [
   "node_modules/@popperjs/core/dist/umd/popper.min.js",
   "node_modules/bootstrap/dist/js/bootstrap.min.js",
 ],

app.service.ts

declare var bootstrap: any;

private tooltipList = new Array<any>();

enableTooltip() {
  // Bootstrap tooltip initialization
  const tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'));
  const tooltipListNewTooltips = tooltipTriggerList.map(tooltipTriggerEl => {
    return new bootstrap.Tooltip(tooltipTriggerEl);
  });
  this.tooltipList.push(...tooltipListNewTooltips);
}

hideAllTooltips() {
  this.tooltipList;
  for (const tooltip of this.tooltipList) {
    tooltip.dispose();
  }
  this.tooltipList = new Array<any>();
}

1
投票

最好的方法是创建一个

Attribute Directive

安装引导程序

npm install bootstrap

styles.scss

中导入 Bootstrap SCSS
// For Setting Project Specific Bootstrap Variable. Like $primary Color
@import "assets/scss/variables.scss";

// Import Bootstrap
@import "../node_modules/bootstrap/scss/bootstrap.scss";

// App Specific components
@import "assets/scss/app.scss";

在 angular.json 中导入 Bootstrap Bundle JS -> 架构师 -> 构建 -> 选项

"scripts": [
  "node_modules/bootstrap/dist/js/bootstrap.bundle.min.js"
]

boostrap
中将
src/typings.d.ts
声明为全局变量。 如果不存在则创建此文件。

declare var bootstrap: any;

创建指令工具提示:

src/app/_components/tooltip.directive.ts

import { AfterViewInit, Directive, ElementRef, OnDestroy } from '@angular/core';

@Directive({
  selector: '[bTooltip]'
})
export class TooltipDirective implements AfterViewInit, OnDestroy {
  private tooltip: any;

  constructor(private elementRef: ElementRef) {}

  ngAfterViewInit() {
    const domElement: HTMLElement = this.elementRef.nativeElement;
    this.tooltip = new bootstrap.Tooltip(domElement);
  }

  ngOnDestroy(): void {
    this.tooltip.dispose();
  }
}

src/app/_components/tooltip.directive.spec.ts

import { ElementRef } from '@angular/core';
import { TooltipDirective } from './tooltip.directive';

describe('TooltipDirective', () => {
  it('should create an instance', () => {
    const elementRefMock: ElementRef = {} as ElementRef;
    const directive = new TooltipDirective(elementRefMock);
    expect(directive).toBeTruthy();
  });
});

src/app/app.module.ts
中声明工具提示指令:

import { TooltipDirective } from './_components/tooltip.directive';

@NgModule({
  declarations: [
    ...
    TooltipDirective
  ]
})

使用如下指令:

<a bTooltip title="Your Message"></a>

现在您将能够使用工具提示及其所有属性,例如

data-bs-placement

我认为通过类似的方法,您可以使用 Angular 中的大多数 Bootstrap 组件。


0
投票

尝试在你的 ts 文件中编写此代码:

var tooltipTriggerList = [].slice.call(document.querySelectorAll('[data-bs-toggle="tooltip"]'))
var tooltipList = tooltipTriggerList.map(function (tooltipTriggerEl) {
  return new bootstrap.Tooltip(tooltipTriggerEl)
})

来源:https://getbootstrap.com/docs/5.0/components/tooltips/#example-enable-tooltips-everywhere


0
投票

您可以检查您的

<button>
<a>
标签是否处于
*ngIf
条件内。我的例子就发生过这种情况。示例:

<a *ngIf="conditionVariable" [routerLink]="['/home']" class="btn btn-primary btn-sm">BUTTON</a>

<div *ngIf="conditionVariable">
    <a [routerLink]="['/home']" class="btn btn-primary btn-sm">BUTTON</a>
</div>

如果您有这样的内容,您应该将其替换为:

<a [hidden]="conditionVariable" [routerLink]="['/home']" class="btn btn-primary btn-sm">BUTTON</a>

<div [hidden]="ConditionVariable">
    <a [routerLink]="['/home']" class="btn btn-primary btn-sm">BUTTON</a>
</div>

0
投票

这里的人们问我们是否需要在实现引导工具提示的所有类中添加该方法。 我认为有几个可行的解决方案

  1. 我们可以在应用程序组件中使用路由器事件并订阅它,一旦我们完成子组件的渲染,然后运行此逻辑。 例如,在 ngOnInit 应用程序组件中使用以下代码

    this.routerEvents.subscribe((事件:事件) => { if(事件实例导航结束) { Array.from(document.querySelectorAll('按钮[data-bs- 切换=“工具提示”]')) .forEach(tooltipNode => 新的 bootstrap.Tooltip(tooltipNode)) }

    })

  2. 使用指令并使用 renderer2 和 ElementRef 在那里使用逻辑,但请确保不使用文档和数组,而只使用 renderer2 和 ElementRef

此处带有指令的示例

       <button type="button" appTooltip="Tooltip Data" class="btn btn-secondary me-2">
                  Hover on me
       </button>
    
      import { AfterViewInit, Directive, ElementRef, Input, Renderer2 } from '@angular/core';
declare var bootstrap: any;


@Directive({
  selector: '[appTooltip]'
})
export class BootstrapTooltipInitDirective implements AfterViewInit {

  constructor(private el: ElementRef, private renderer: Renderer2) { }

  @Input() placement = 'top';
  @Input() appTooltip = '';

  ngAfterViewInit(): void {
    this.renderer.setAttribute(this.el.nativeElement, 'data-bs-toggle', 'tooltip');
    this.renderer.setAttribute(this.el.nativeElement, 'data-bs-placement', this.placement);
    this.renderer.setAttribute(this.el.nativeElement, 'title', this.appTooltip);
    new bootstrap.Tooltip(this.el.nativeElement);
  }

}

0
投票

你可以使用这个: ngAfterViewInit(){ const exampleEl = document.getElementById('tool') as HTMLDivElement; const tooltip = new bootstrap.Tooltip(exampleEl, {animation: true, trigger:"hover",title:"需要帮助吗?"}) }

© www.soinside.com 2019 - 2024. All rights reserved.