Is it possible to incorporate Angular components into SVG templates?

After discovering that template files can now be saved as .svg rather than .html, I decided to create svg components for use like so.

main.component.svg

<svg>
    <my-svg-component></my-svg-component>
</svg>

mySvg.component.svg

<text x="0" y="60">test text</text>

However, when I received an error stating that <text></text> was not a recognized element, I made the following modification:

<svg:text x="0" y="65">test text</svg:text>

The error disappeared, but nothing is rendering. When I added the script directly into the <svg> tag in the main.component.svg file without using svg: at the beginning, it worked fine.

Do I need to do something specific in the mySvg.component template to make this work as a reusable component or should all of the SVG generation happen within one single template?

UPDATE

I attempted to utilize SVG's <foreignObject> like this

<svg>
    <foreignObject>
        <my-svg-component></my-svg-component>
    </foreignObject>
<svg>

This method also did not yield results. Testing with a paragraph tag, I realized that I had to use <xhtml:p> for it to render properly. Even after adding the xhtml: part to my component, there was still no visible output. Now, I am contemplating if there may be an angular: equivalent that could be used instead.

Answer №1

One possible way to achieve this is as follows:

Here is the template structure:

<svg>
  <g svgtext></g>
</svg>

This is how the svg component can be implemented:

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

@Component({
  selector: '[svgtext]',
  template: `<svg:text x="0" y="65">test text</svg:text>`,
  styles: [`your styles come here`]
})
export class HelloComponent {

}

The key is to connect your svg component with another svg element (group - g) using an attribute selector. By doing this, the resulting template remains a valid SVG and allows for the rendering of text.

Take a look at this example on StackBlitz: https://stackblitz.com/edit/angular-fd1tcd

If you use component selectors with tags, it will break the SVG schema and prevent the browser from rendering the SVG properly. However, by utilizing a group (which is a valid svg container), we can avoid this issue and inject additional HTML content directly within that group.

For further insights, check out this informative article by Tero:

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

Steps for generating a current date and a date one year in the past

In my WebService, I need to update the DATEFIN to today's date and the DATEDEBUT to a date that is one year prior. Currently, the setup looks like this: see image here At the moment, I am manually inputting the dates. How can I automate this proces ...

Navigating through unidentified object in Typescript

I'm working with an object that has an unknown format, specifically a users' CSV file. My task is to iterate through the keys to identify certain keys, such as phone numbers referenced as phoneNumbers1, phoneNumbers2, and so on in the .csv file. ...

Integrating Paytm with Angular 6: A Step-by-

I am currently facing an issue where I am not being redirected to the paytm server's page after using the HTML form for integrating paytm in PHP. Can anyone provide assistance with this matter? ...

Tips for including extra space before or after '{' and '}' in WebStorm?

While I have some experience with JetBrains products and setting styles for my files, I am struggling to configure my .tsx file to display the desired style. It appears that changes made in the TypeScript section are not affecting my .tsx file. In the ima ...

Patience is key as we anticipate the promise's response to fill out the

Hello, I am currently developing an angular/typescript application and I have been researching about promises. However, I am still struggling to fully understand it. I would greatly appreciate your assistance. I have a function called getUserById() which ...

Does the submit button function even without filling in the required fields?

After creating a form with 20 fields, I encountered an issue. Out of those fields, there are 10 mandatory ones. When attempting to submit the form, only the mandatory input fields display a red border without showing an error message. Despite this, the sub ...

Typescript error in Express: The property 'body' is not found on the type 'Request'

I found this code snippet: import bodyParser from 'body-parser'; import express, { Router } from 'express'; const router: Router = express.Router(); router.use(bodyParser.json()); router.post('/api/users/signup', (req: expr ...

Should I return X in async functions, or should I return "Promise.Resolve(X)"?

I've always found this to be a tricky concept to fully grasp. Let's delve into async functions in Typescript. Which implementation is accurate? async function asyncFunctionOne(string1: string, string2: string, string3: string) { var returnOb ...

Tips for testing the RXJS pipe method using Jasmine

I need assistance with covering the pipe function of RXJS in Angular/Jasmine. An error is popping up: TypeError: this.element.children.pipe is not a function Here's the snippet of code causing the issue: ngOnInit() { this.element.children.pipe( ...

Uncertainty arises when trying to understand the callback function supplied to the `addEventListener` method in JavaScript

Question: I was recently exploring JavaScript's native addEventListener function. Typically, we use it like this: js selectElement.addEventListener('change', (event) => { const value = event.target.value }); However, when studying the ty ...

Why is it that the game board component is not appearing on my HTML page?

I am currently facing an issue with a loop in my Angular html file: <div class="board" #board> <div class="row" *ngFor="let row of this.board; let i = index"> <div *ngFor=" ...

How can I create a dashed border for a pie chart using highcharts?

Is there a way to change the default solid border of a pie highchart to dashed? This modification is only necessary for pies without data or with negative data values. Perhaps it's possible to redraw the SVG of the border, like in this example: https: ...

The JSX element with type 'Component' does not support any construct or call signatures at this time

I am facing an issue with the following code snippet const pageArea = (Component:ReactNode,title:string) => ({ ...props }) => { return ( <> <div> { Component && (<Component { ...

The or operator in Typescript does not function properly when used as a generic argument

My current configuration is as follows: const foo = async <T>(a): Promise<T> => { return await a // call server here } type A = { bar: 'bar' } | { baz: 'baz' } foo<A>({ bar: 'bar' }) .then(response =& ...

Here is the rewritten text: "Create a TypeScript interface that returns various types of

myFunctionResult interface { abc: string } function myFunction(): myFunctionResult { if(something) return { abc:'abc' } //this is fine return 'result' //however, this line is causing a warning } I need to declare two different re ...

Navigating from the root view to a (grand)child view with Angular2: Mastering Direct Links

I am currently exploring Angular 2 and have encountered a perplexing issue that I need assistance in debugging. An Illustrative Scenario In my project, I have an AppComponent that manages the fundamental level routing. Each subsequent level of routing is ...

Verify if the keys are present within the object and also confirm if they contain a value

How can we verify keys and compare them to the data object? If one or more keys from the keys array do not exist in the object data, or if a key exists but its value is empty, null, or undefined, then return false; otherwise, return true. For example, if ...

Creating a universal wrapper function to serve as a logging tool?

Currently, I am working on a generic JS function that can wrap any other function. The purpose of this wrapper is to execute the wrapped function, log the input and output events, and then return the output for "transparent" logging. However, as I attempt ...

Prevent Angular Material Autocomplete from automatically updating the input field

As part of my project, I am working on creating a country autocomplete input feature. To make the input more reusable, I am looking to turn it into a component using the ControlValueAccessor interface. The goal is to have the component accept a FormControl ...

Can classes from an external package be imported into an Angular library within an Angular app using Openlayers?

I am currently developing an Angular library that configures an OpenLayers map as an Angular component. The component is functioning properly, but I need to access classes and constants from a package imported by the library, specifically OpenLayers. To w ...