Incorporating an external SVG file into an Angular project and enhancing a particular SVG element within the SVG with an Angular Material Tooltip, all from a TypeScript file

Parts of the angular code that are specific

|SVG File|

<svg version="1.0" xmlns="http://www.w3.org/2000/svg"
     width="950" height="450" viewBox="0 0 1280.000000 1119.000000"
     preserveAspectRatio="xMidYMid meet">
<circle r="50px" cx="650" cy="968" fill="red" stroke="black" visibility="visible"/>
  <rect x="650.117" y="968.413" width="1000" height="800" fill="green" visibility="visible"/>
</svg>

|HTML File|

<object #svgmyimage>
</object>

|Type Script File|

 @ViewChild('svgmyimage') imageSvg?:ElementRef;

 ngOnInit() {
    this.reset();
    this.httpClient
          .get(`assets/svgimages/image1.svg`, { responseType: 'text' })
          .subscribe((value: string) => {
            this.svgStr = value;
//             console.log(this.svgStr);
            this.drawImage();
          });

  }

  drawImage() {
    if (this.imageSvg && this.svgStr) {

      this.imageSvg.nativeElement.innerHTML = this.svgStr;

      if(this.imageSvg.nativeElement.children[0])
      {
          this.imageSvg.nativeElement.children[0]setAttribute('visibility', 'visible');
          this.imageSvg.nativeElement.children[1]setAttribute('fill', 'yellow');
      }

    }
  }

It is possible to access and modify attributes in order to incorporate an Angular Material Tooltip. The tooltip property can be utilized within the HTML file itself, with the requirement that the entire SVG code is contained within the HTML rather than being referenced as an external file. Assistance is needed on how to achieve this.
As

this.imageSvg.nativeElement.children[0]setAttribute('matTooltip', 'information');

does not make sense since Tooltip is not a property of the SVG. Therefore, the query remains on how to add a tooltip specifically to the circle element in the externally linked SVG file from the Typescript file. The objective is to implement a tooltip solely for the circle in the SVG!

Answer №1

When creating a tooltip, there are two approaches we can take: using popperjs (such as ng-bootstrap or bootstrap) or utilizing the built-in cdkoverlay (like material angular).

To implement ckdoverlay, we need to inject Overlay in the constructor, create a Portal, and then attach it on mouseenter and detach it on mouseleave. If we prefer using HTMLElements, we can create a class to encapsulate all the functionality.

 // code example goes here

An important aspect when using DomPortal is that it remains in the .html when not attached—we can also opt for a TemplatePortal, but that requires injecting a ViewContainerRef as well. To show/hide the tooltip, we can toggle its visibility with typical CSS:

.tooltip {
  ...
  display:none;
}

.tooltip[data-show] {
  display:block
}

Another crucial detail is indicating the position conveniently as top, bottom, left, or right. This can be achieved by defining an object like this:

// Code snippet goes here 

With this class, we have two options: either use it as a directive or integrate it into a component that injects OverLay.

// Code snippet goes here 

In an HTML example, you can include the directive as follows:

// Code snippet goes here 

In case you prefer using the library in a TypeScript component, ensure to properly initialize and later destroy the TooltipOverLay instance:

// Code snippet goes here 

You can find an example showcasing both methods in the following stackblitz. Alternatively, you can explore another demonstration by forking GRM's code and adapting it to attach a tooltip to an inner element of an SVG in this modified stackblitz.

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

Travis CI's TypeScript build process detects errors before Mocha has a chance to catch them

Instead of a bug, the TypeScript compiler is doing its job but causing my Travis builds to fail. In my package, I have a function named completeRound which accepts a number as its first argument and 3 optional arguments. Since it's in TypeScript, I s ...

"Utilizing SVG format to manipulate text, adjusting font size within tspan elements

There seems to be an issue with the font size on SVG. Even though both the SVG and paragraph have a font-size of 16px, they appear different. I would like the font size in the SVG to match that of the paragraph. Another concern is how to center <tspan ...

"Encountering a 'Module Not Found' error in Node.js after

Recently, I added a node-module to my project using the command: npm install typescript --save-dev However, when I tried running: tsc Windows displayed an error message indicating that "tsc" is an unknown command. Strangely, this issue does not occur o ...

The declaration file for the 'express' module could not be located

Whenever I run my code to search for a request and response from an express server, I encounter an issue where it cannot find declarations for the 'express' module. The error message transitions from Could not find a declaration file for module & ...

Icons from Material UI individually designed

Is it feasible to save individual icons from the MUI package as SVGs in an app's directory for enhanced performance and reduction of external dependencies? ...

What causes the left click to not trigger in Kendo's Angular Charts?

My homepage features a simple bar chart that displays correctly, but I am having trouble capturing the left click event (the right click works fine). This is an example of code from my template: <kendo-chart *ngIf="(dataExists | async)" [ ...

Encountered Typescript errors TS1110 and TS1005

Error in TypeScript: typings/node/node.d.ts(83,23): Type expected. TypeScript issue: typings/node/node.d.ts(1830,52): Expected '=' sign. My TypeScript compilation is failing at node.d.ts, despite multiple attempts to reinstall it. ...

There was an unhandled exception that occurred due to a missing file or directory with the lstat error on 'D:a1s ode_modulesquill'

ngx-quill is causing issues in production, any suggestions? I am currently using "ngx-quill": "^13.4.0", but it is unable to find Quill on my server even though it works locally. The problem persists in the pipeline... An unhandled exception has occurred ...

Mysterious Chrome glitch causes SVG element to shift down by 2 pixels

I am currently facing an issue with creating image links from an SVG spritesheet that is causing cross-browser problems between Chrome, Safari, and Firefox. Here are some of the anchor tags I am using: <a href="#" id="twitter-logo" class="socialIcon"&g ...

The Append method in FormData is not functioning properly within Angular

I'm facing a challenge in my Angular application where I need to enable image uploads to the server. The issue arises when attempting to add a selected file to the newly created FormData object. Below is the relevant TypeScript component snippet: ima ...

Encountering a "Multiple registrations of the method 'get' on the path '../api/' error" with Swagger

I am utilizing OpenAPI / Swagger in an Angular application built on .NET Core, and I am facing the error "The method 'get' on path '../api/' is registered multiple times" while generating frontend TypeScript code using NSwag Studio. Fro ...

Instructions for disabling editing for a specific cell within an inline editable row in primeNG

I am currently using PrimeNG DataTable with Angular, where the rows are editable as shown in the example in the documentation: https://www.primefaces.org/primeng/#/table/edit. However, I am facing an issue where I want to exclude one cell from being editab ...

Why is the selected option not visible in the Angular 8 drop-down?

This is a commonly asked question, but my situation seems to be unique. None of the existing answers have provided a solution for my specific issue. Here is the code that I am working with: <form (ngSubmit)="getExceptions(f)" #f="ngForm"> ...

To trigger a Bootstrap 5 modal in a child component from a button click in the parent component in Angular without the need to install ng-bootstrap is possible with the following approach

To achieve the functionality of opening a modal in a child component upon clicking a button in the parent component without using ngx-bootstrap due to restrictions, one approach is to add data-bs-target and data-bs-toggle attributes to the button. Addition ...

Using inline style instead of relying on the quill editor's built-in classes, as classes may not be accessible in order to render HTML effectively

I have integrated the ngx-quill editor into my Angular project as the rich text editor. I plan to save the generated HTML in a database and display it on various browsers using innerHTML. Since the styling is done through a class attribute that references ...

Tips for making use of incomplete types

Is there a way to reference a type in TypeScript without including all of its required fields, without creating a new interface or making all fields optional? Consider the following scenario: interface Test { one: string; two: string; } _.findWhe ...

How can you inject the parent component into a directive in Angular 2, but only if it actually exists?

I have developed a select-all feature for my custom table component. I want to offer users of my directive two different ways to instantiate it: 1: <my-custom-table> <input type="checkbox" my-select-all-directive/> </my-custom-table> ...

Utilizing Node.js and Jasmine: Preventing the invocation of a Promise function to avoid executing the actual code results in DEFAULT_TIMEOUT_INTERVAL

There is a function below that returns a promise. public async getAverageHeadCount(queryParams: Params, childNode: any, careerTrackId: string): Promise<Metric> { const queryId = this.hierarchyServiceApiUrl + "rolling-forecast/ahc/" + q ...

Display streaming data continuously within an HTML page using Angular 16

Currently, I am actively developing a stream API that receives data with a 'Content-Type' of 'text/event-stream'. Below is a snippet from my stream.service.ts: connectToSse(): Observable<any> { return new Observable((observer ...

What advantages does NgRx offer that Signal does not provide?

Signals are a recent addition to the Angular framework. In comparison to Signals, what unique benefits does the NgRx component store or other state management options provide? Are there any functionalities offered by the NgRx component store that cannot ...