有没有办法使用bootstrap 4中的工具提示功能?
我们已经使用npm install安装了bootstrap 4、tether和jquery,
在文档中,我们必须用javascript编写jquery代码,
$(function () [
$('[data-toggle="tooltip"]').tooltip()
})并将此代码添加到html中,
data-toggle="tooltip" data-placement="top" title="Tooltip on top"我们已经尝试添加html代码,但是不起作用,显然我们必须编写jquery代码,但是我们可以使用typescript在angular 4中编写jquery语法吗?那么在angular 4中该把语法放在哪里呢?
发布于 2017-09-11 12:33:04
将jquery、tether和bootstrap脚本添加到angular-cli.json
"scripts": [
"../node_modules/jquery/dist/jquery.min.js",
"../node_modules/tether/dist/js/tether.min.js",
"../node_modules/bootstrap/dist/js/bootstrap.min.js"
],然后转到所需的组件。然后键入declare var $: any;。
import { Component, OnInit } from '@angular/core';
// this line will allow you to use jQuery
declare var $: any;
@Component({
...
})将您的内容放入ngOnInit() { /* Content here. */ }中。
ngOnInit() {
$(() => {
// Testing jQuery
console.log('hello there!');
});
}我不喜欢在angular中使用jQuery,这不是一个好的做法,试着搜索构建在angular之上的工具提示,或者使用Renderer2 https://angular.io/api/core/Renderer2,或者为此构建你自己的指令,Angular Material2有你可能想要使用的工具提示组件,非常容易在typescript中实现。
https://material.angular.io/components/tooltip/overview
对于完整的文档。
发布于 2017-10-19 08:03:30
我是通过创建一个指令来实现的。
import { Directive, OnInit, Inject, ElementRef } from '@angular/core';
import { JQUERY_TOKEN } from './jquery.service';
@Directive({
selector: '[data-toggle="tooltip"]'
})
export class TooltipDirective implements OnInit {
private el: HTMLElement;
constructor(elRef: ElementRef, @Inject(JQUERY_TOKEN) private $: JQueryStatic) {
this.el = elRef.nativeElement;
}
ngOnInit() {
this.$(this.el).tooltip();
}
}这是import语句中提到的jquery.service文件
import { InjectionToken } from '@angular/core';
export const JQUERY_TOKEN = new InjectionToken<JQueryStatic>('jQuery');然后添加到模块中
import { NgModule } from '@angular/core';
import { TooltipDirective } from './tooltip.directive';
import { JQUERY_TOKEN } from './jquery.service';
export let jQuery: JQueryStatic = window['jQuery'];
@NgModule({
imports: [
// ...
],
declarations: [
TooltipDirective
],
providers: [
{ provide: JQUERY_TOKEN, useValue: jQuery }
]
})
export class MyModule {}然后,只需将其添加到需要它的组件中。例如,在我的app.component.ts文件中,我所要做的就是在顶部添加以下一行,以使其与模板一起工作:
import { TooltipDirective } from './tooltip.directive';https://stackoverflow.com/questions/46147318
复制相似问题