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

2023-12-24

我在用这个答案 https://stackoverflow.com/a/35385518/10684507将 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
    }
  }
}

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

FIX

Use a type assertion as shown:

代替:

anchor.getAttribute('href')

Use:

(<Element>anchor).getAttribute('href')
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在 Angular 中获取 DOM 节点属性 的相关文章

随机推荐