如何在Angular中获取DOM节点属性

时间:2019-05-19 15:46:49

标签: javascript angular typescript dom

我正在使用this answer将HTML字符串转换为Angular中的DOM元素。

问题是我无法获得Node的属性。 getAttribute()无法使用,因为打字稿会抱怨No property getAttribute on Node

代码在下面(简体)。

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

3 个答案:

答案 0 :(得分:2)

TypeScript的API视图。目前还没有办法说foo.parentNode的类型取决于foo的类型。当前推断它始终为Node类型,并且Node不包含API querySelector(可在Element上使用)

FIX

Use a type assertion as shown:

代替:

anchor.getAttribute('href')

使用:

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

答案 1 :(得分:1)

您可以改用NodeListOf界面。

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

答案 2 :(得分:0)

您可以将anchors属性设置为任何

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

并且不应该是Noedlist数组,因为您的代码引用了上一行中的内容-

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