What are the steps for implementing a tooltip in Angular 4 using Bootstrap tether and jQuery that have been installed from npm

Is there a way to enable tooltip functionality in Bootstrap 4?

We've successfully installed Bootstrap 4, Tether, and jQuery using npm install.

The documentation suggests writing jQuery code in JavaScript like this:

$(function () {
  $('[data-toggle="tooltip"]').tooltip();
})

Additionally, the code needs to be added to the HTML like so:

data-toggle="tooltip" data-placement="top" title="Tooltip on top"

We attempted to integrate the HTML code but it is not working. Should we write jQuery syntax in Angular 4 which uses TypeScript? If so, where should the syntax be placed in Angular 4?

Answer №1

To integrate jQuery, tether, and bootstrap scripts into your Angular project, follow these steps:

"scripts": [
  "../node_modules/jquery/dist/jquery.min.js",
  "../node_modules/tether/dist/js/tether.min.js",
  "../node_modules/bootstrap/dist/js/bootstrap.min.js"
],

Next, navigate to the component where you want to use jQuery and declare it as follows: declare var $: any;.

import { Component, OnInit } from '@angular/core';

// Declare jQuery
declare var $: any;

@Component({
  ...
})

Insert your content within the

ngOnInit() { /* Content here. */ }
function.

ngOnInit() {
  $(() => {
    // Testing jQuery
    console.log('hello there!');
  });
}

While using jQuery in Angular is not recommended, you can explore alternatives such as Angular Material2 tooltips or creating your own directive using Renderer2. Check out the Angular Material2 tooltip component for a TypeScript-friendly option.

https://material.angular.io/components/tooltip/overview

For comprehensive documentation, visit:

https://github.com/angular/material2

Answer №2

My solution involved the creation of a custom directive.

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

The jquery.service file is referenced in the import statement above.

import { InjectionToken } from '@angular/core';

export const JQUERY_TOKEN = new InjectionToken<JQueryStatic>('jQuery');

Afterwards, it needs to be added to the module like so:

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

Finally, include the directive in the desired component. For example, by adding one line in the app.component.ts file:

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Leverage the inherent capabilities of jQuery to seamlessly transmit form data via ajax using the pre-existing

Snippet of Code: <?php if ($_SERVER['REQUEST_METHOD'] == 'POST'){ header('Content-Type: application/json'); echo json_encode($_POST); exit(0); } ?> <html> <head> <titl ...

Using JavaScript to retrieve data from a JSON file and showcase it on a jQuery mobile webpage

I am struggling to retrieve JSON data from a PHP URL using JavaScript and display it within a JQuery mobile "li" tag as a category list. Despite spending the last 8 hours on it, I can't seem to get it working using the code provided below. Any help wo ...

Bundling JSPM with an external system JS file

Currently, I am loading my Angular2 file as a System js module from a CDN. Within my project, I have multiple files importing various System js modules of Angular2. However, I am now looking to bundle my local JavaScript files using JSPM. But when I ente ...

Unable to locate the last form control with the specified name

I have a project that involves displaying images on our NAS using Angular 17. On the main page, I have 3 mat-form-fields. Strangely, when I add the last mat-form-field, I encounter the following error - ERROR Error: Cannot find control with name: 'num ...

Error encountered with jQuery UI datepicker beforeShowDay function

After installing jquery-ui's datepicker, I encountered an issue while attempting to implement an event calendar. The datepicker was working fine until I tried to register the beforeShowDay handler using the following code: $('#datePicker'). ...

Angular - Using @HostListener to prevent page refresh entirely

Using @HostListener to prevent window reload. The code implementation is as follows - @HostListener('window:beforeunload', ['$event']) unloadNotification($event: any) { let checkSave = true; for( let index = 0; index < this.data. ...

The CSS Bootstrap 4 class 'input-group-append' is not functioning properly. Just recently, the styles were displaying correctly

My web application using AngularJS 1.7.8, jQuery 3.3.1, Bootstrap 4.3.1, and various other CSS and JS libraries worked seamlessly last week. However, today I noticed an issue with the button visualization. To Replicate: Visit openskymap.org to see my d ...

Is it possible to showcase a cycling gallery with thumbnails and captions using Jquery Cycle?

Currently, I am using the JQuery plugin cycle() created by Malsup. My goal is to showcase images in a gallery format, along with a list of thumbnails and captions below each thumbnail. Here's the code snippet I have implemented: <div id="slideshow ...

What is a Mongoose Schema type in TypeScript and how can it be used as a custom

https://i.stack.imgur.com/mtlRi.png Could anyone assist me with storing a custom object that includes attributes from the StationRating interface? ...

What is the best way to embed an Angular directive within another directive?

Is there a way to create a child directive within a parent directive and utilize the modal attribute in the child directive to inject HTML from a template into a Bootstrap modal? The child directive should have attributes for question and modal, each with ...

Align all elements at the center in Bootstrap 4

My goal is to create a straightforward registration form with minimal elements, all centered on the page. However, I ran into an issue when using Bootstrap - all my elements are shrinking in size. For instance, an element that should be 100% width becomes ...

Retrieving the Href attribute from a designated div class with JQuery

I'm currently developing a Google Chrome extension where I need to extract the source code of a webpage using a jQuery get function. Here is how I implemented it: $.get(link,function(data){ // The entire source code of the link will be stored in the ...

Refresh the table every couple of seconds

I need to regularly update a table every two to three seconds or in real-time if possible. The current method I tried caused the table to flash constantly, making it difficult to read and straining on the eyes. Would jQuery and Ajax solve this issue? How c ...

Flexbox failing to properly align items once text wraps in container

Having difficulty using a flexbox container with bootstrap 4 to center align my elements horizontally. This is the code snippet I have been working on: <div class="d-flex flex-column align-items-center"> <img class="rounded-circle" height="5 ...

The .val method works without any issues in the emulator, but fails to function properly on the actual

Currently, I am developing an app with a list view featuring a roster of students. The goal is for users to be able to tap on a student's name and have a form automatically populate with that student's details for viewing or editing. While this f ...

How can I use jQuery to display a div alongside the element that is currently being hovered over?

Imagine having multiple divs similar to these: UPDATE: <div class="ProfilePic"> <a href="#"> <img src="lib/css/img/profile_pic1.png" alt="" class="ProfilePicImg"/> </a> <div class="PopupBox" style="display: ...

The Bootstrap carousel slider is functioning properly, however, the images are not displaying

I am experiencing an issue with my carousel. I have been developing a project and utilizing the bootstrap-4 carousel slider. It functions properly when I run it on my localhost, displaying all the images as expected. However, after publishing the project o ...

Is there a way to make an angular component reuse itself within its own code?

I am dealing with a parent and child component scenario where I need to pass data from the parent component to the child component. The aim is to display parentData.name in the child component when parentData.isFolder===false, and if parentData.isFolder=== ...

Managing multiple Sequelize DB connections in NestJS: A guide

I recently came across the example in the NestJS documentation regarding setting up a Sequelize DB connection. I'm curious about how to connect to multiple databases using Sequelize and TypeScript with NestJS. Can anyone provide guidance on this? ...

Effortless script to make a URL request and display the response status | using JavaScript with jQuery

Is there a way to use JavaScript or jQuery to request a URL or website address and display the response code? For example: request www.google.com if (response_code = 200) { print "website alive" } else if (response_code = 204) { print "not found"; } ...