4

I am using this answer to convert a HTML string to DOM elements in Angular.

The problem is that I can't get attributes of Node. getAttribute() cannot be used since typescript will complain that No property getAttribute on Node.

Code is below (simplified).

import { AfterViewInit, Renderer2 } from '@angular/core';

export class MockComponent implements AfterViewInit {
  constructor(private renderer: Renderer2) {}

  private mockString = '<a href="#test1">test 1</a>'

  ngAfterViewInit(): void {
    const template = this.renderer.createElement('template');
    template.innerHTML = this.mockString.trim();
    const anchorNodes: NodeList = template.content.querySelectorAll('a');
    const anchors: Node[] = Array.from(anchorNodes);
    for (const anchor of anchors) {
      // how to get attributes of anchor here?
      // anchor.getAttribute('href') will be complained
    }
  }
}
funkid
  • 329
  • 1
  • 5
  • 20

3 Answers3

4

TypeScript's view of the API. At the moment there is no way to say that the type of foo.parentNode depends on the type of foo. Currently it is inferred to always be of type Node and Node does not contain the API querySelector (available on Element)

FIX

Use a type assertion as shown:

Instead of:

anchor.getAttribute('href')

Use:

(<Element>anchor).getAttribute('href')
1

You can use the NodeListOf interface instead.

const anchorNodes: NodeListOf<HTMLAnchorElement> = template.content.querySelectorAll('a');
const anchors: HTMLAnchorElement[] = Array.from(anchorNodes);
Reactgular
  • 43,331
  • 14
  • 114
  • 176
0

You can set the anchors property as an array of any

const anchors: any[] = Array.from(anchorNodes);

and shouldn't it be Noedlist array as your code refers to that in the previous line-

const anchors: NodeList [] = Array.from(anchorNodes);
Shofol
  • 453
  • 7
  • 21