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

fun*_*kid 4 javascript dom typescript angular

我正在使用这个答案将 HTML 字符串转换为 Angular 中的 DOM 元素。

问题是我无法获取 的属性NodegetAttribute()无法使用,因为 typescript 会抱怨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
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

Jac*_*nde 5

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

使固定

Use a type assertion as shown:

代替:

anchor.getAttribute('href')
Run Code Online (Sandbox Code Playgroud)

使用:

(<Element>anchor).getAttribute('href')
Run Code Online (Sandbox Code Playgroud)