Encountering a Type Error while attempting to generate an HTML element from the typescript file within Angular 7

Attempting to convert some JavaScript code into TypeScript and create an HTML element from the ts. Here is the function causing issues:

createSvgElem(name: string, attributes: any) {
    let node = document.createAttributeNS('http://www.w3.org/2000/svg', name);
      for (let name in attributes) {
        node.setAttribute()
      }
  }   

An error is thrown:

Property 'setAttribute' does not exist on type 'Attr'.

The original format (working perfectly within a js file):

HocrProofreader.prototype.createSvgElem = function (name, attributes) {
    var node = document.createElementNS('http://www.w3.org/2000/svg', name);
    for (var name in attributes) {
        node.setAttribute(name, attributes[name]);
    }
    return node;
},

What is the correct way to handle this?

[EDIT] After changing to createElementNS, it works fine. However, I am unable to access the linkedNode property

const rectNode = this.createSvgElem('rect', {
          'x': options.bbox[0],
          'y': options.bbox[1],
          'width': options.bbox[2] - options.bbox[0],
          'height': options.bbox[3] - options.bbox[1],
          'id': node.id,
          'bbox': node.title,
          'class': className
        });
        parentRectsNode.appendChild(rectNode);

        // cross-link both nodes:
        rectNode.linkedNode = node;
        node.linkedNode = rectNode;
      }

Answer №1

One of the main reasons for the error is that 'setAttribute' is not a property of the 'Attr' type. In TypeScript, 'setAttribute' exists as a method on the 'Element' type. When the 'createAttributeNS' function returns an attribute, the 'Attr' type is implicitly assigned to the 'node' variable.

The underlying issue lies in the fact that 'setAttribute()' adds the specified attribute to an element and assigns it a value, which cannot be done directly to an attribute in JavaScript or TypeScript.

Update after resolving the initial problem:

When using the 'createElementNS' method with the namespace 'http://www.w3.org/2000/svg', it returns an 'SVGElement.' Therefore, the TypeScript compiler automatically assigns the 'SVGElement' type to the 'node' variable. Consequently, any return node from the function will also have the 'SVGElement' type, causing the error when trying to access the non-existent 'linkedNode' property.

If you need to assign custom objects to the 'rectNode,' consider using the 'any' type:

const rectNode:any = this.createSvgElem('rect', {
          'x': options.bbox[0],
          'y': options.bbox[1],
          'width': options.bbox[2] - options.bbox[0],
          'height': options.bbox[3] - options.bbox[1],
          'id': node.id,
          'bbox': node.title,
          'class': className
        });
        parentRectsNode.appendChild(rectNode);

        // cross-link both nodes:
        rectNode.linkedNode = node;
        node.linkedNode = rectNode;
      }

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

Clicked but nothing happened - what's wrong with the function?

For my project, I have incorporated tabs from Angular Material. You can find more information about these tabs here. Below is the code snippet I am using: <mat-tab-group animationDuration="0ms" > <mat-tab></mat-tab> < ...

The 'changes' parameter is inherently defined with an 'any' type.ts(7006)

Encountering an error and seeking help for resolution. Any assistance would be highly appreciated. Thank you. Receiving this TypeError in my code. How can I fix this issue? Your guidance is much appreciated. https://i.sstatic.net/cWJf4.png ...

Encountered the issue of No suitable overload found for this call in React with Typescript

While working on a React project, I encountered an issue with my form component's onSubmit event showing an error message "No overload matches this call". The code snippet causing the problem is as follows: <StyledForm onSubmit={this.handleSave}&g ...

Important notice: It is not possible to assign refs to function components. Any attempt to do so will result in failure. If you intended to assign a ref, consider

My console is showing a warning when I use the nextJs Link component. Can someone assist me in resolving this issue and providing an explanation? Here is the message from the console: https://i.stack.imgur.com/jY4FA.png Below is a snippet of my code: im ...

A helpful guide on retrieving input values using target.querySelector in Angular 6

I'm having trouble retrieving the values from the username and password input fields using target.querySelector. I keep getting an exception that says the value is not found. Can someone please suggest a solution? .html <input type="text" id="us ...

How to retrieve data from a JSON file in Angular 2 using the http get

I am encountering an issue while trying to access a json file using http get. The error message I receive is as follows: Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterable ...

Guide for transferring the body of a table to a different component without disrupting the design aesthetics

In an attempt to reorganize my large table component, I decided to separate its body section into a new component. However, every time I try to do this, the styling of the table breaks (likely due to the new HTML structure in the code). I'm currently ...

Implementing Firebase-triggered Push Notifications

Right now, I am working on an app that is built using IONIC 2 and Firebase. In my app, there is a main collection and I am curious to know if it’s doable to send push notifications to all users whenever a new item is added to the Firebase collection. I ...

Storing multiple items in an array using LocalForage

I have a challenge where I need to add multiple items to an array without overriding them. My initial approach was like this: localForage.getItem("data", (err, results) => { console.log('results', results) // var dataArray ...

Tips for extracting images from an ion-img element when the source is a PHP script that generates a captcha code

For my college project, I am scraping a website to display the results. One issue I'm facing is that the results are protected by a captcha code. I attempted to scrape using a node HTML parser, but when I extracted the src attribute, it pointed to c ...

Maintaining the Continuity of an Observable Stream Post Error Emission

Have you ever wondered how to handle errors from an observable without ending the stream? For instance, when making HTTP calls and encountering a 404 error or another type of error, throwing an error in the stream will cause it to stop and trigger the err ...

What exactly does the $any() type cast in Angular do and how is it used?

While browsing the Angular.io site, I came across this title: The $any() type cast function There are instances where a binding expression may trigger a type error during AOT compilation and it is not possible or difficult to fully specify the type. To re ...

The type 'MockStoreEnhanced<unknown, {}>' is not compatible with the type 'IntrinsicAttributes & Pick[...]

I'm currently working on creating a unit test for a container in TypeScript. From what I've gathered from various responses, it's recommended to use a mock store and pass it to the container using the store attribute. This method seems to o ...

How can I add a new key value pair to an existing object in Angular?

I'm looking to add a new key value pair to an existing object without declaring it inside the initial object declaration. I attempted the code below, but encountered the following error: Property 'specialty' does not exist on type saveFor ...

Next.js focuses solely on rendering markup and does not run any custom code

I am in the process of creating a website, where currently the only functionality available is to change themes by selecting an option from a dropdown menu (the theme is an attribute that uses CSS variables). Everything was functioning properly, however t ...

Troubleshooting problem with refreshing URL on "ionic serve" mode

After transitioning my project from Ionic 2 to Ionic 3, I've encountered an issue with ionic serve and the rebuilding process. Initially, when I build the project, everything functions as expected. However, I've noticed that the URL in the brows ...

Issues with the linear-gradient feature in Ionic3 are preventing it from properly functioning

I'm currently experimenting with creating a unique gradient color in my Ionic3 variable.sass file. $colors: ( primary: #4471C1, secondary: #32db64, danger: #f53d3d, light: #f4f4f4, dark: #222, newcolor: linear-gradient( ...

Strange compilation issue "Syntax error: Unable to access 'map' property of null" occurs when map function is not utilized

I recently developed a custom useToggle hook that does not rely on the .map() method: import { useState } from "react"; export const useToggle = ( initialValue: boolean = false ): [boolean, () => void] => { const [value, setValue] = us ...

I keep getting a 403 error message when trying to access this endpoint using Angular and the Microsoft Graph API. What could be causing this forbidden response?

Main inquiry I have been working on integrating the REST API of Microsoft Graph into an Angular application (version 10). I diligently followed the guidance provided in a tutorial to connect the Angular app to Microsoft Graph and authenticate a user throu ...

Angular 7 automatically updates array values with the most recent values, replacing any previous values in the process

Currently, I'm working with arrays and utilizing the map function to modify the data. Below is an array of icons: private socialIcons:any[] = [ {"icon":"thumbs-up","operation":"like"}, {"icon":"thumbs-down","operation":"unlike"}, {" ...