admin管理员组

文章数量:1305785

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 plain 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 plained
    }
  }
}

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 plain 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 plained
    }
  }
}
Share Improve this question edited May 19, 2019 at 16:00 funkid asked May 19, 2019 at 15:46 funkidfunkid 6652 gold badges12 silver badges31 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 5

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')

You can use the NodeListOf interface instead.

const anchorNodes: NodeListOf<HTMLAnchorElement> = template.content.querySelectorAll('a');
const anchors: HTMLAnchorElement[] = Array.from(anchorNodes);

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

本文标签: javascriptHow to get DOM Node attributes in AngularStack Overflow