【问题标题】:How to get DOM Node attributes in Angular如何在 Angular 中获取 DOM 节点属性
【发布时间】:2019-10-06 03:28:26
【问题描述】:

我正在使用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
    }
  }
}

【问题讨论】:

    标签: javascript angular typescript dom


    【解决方案1】:

    你可以将anchors属性设置为任意数组

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

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

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

    【讨论】:

      【解决方案2】:

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

      修复

      Use a type assertion as shown:

      代替:

      anchor.getAttribute('href')
      

      用途:

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

      【讨论】:

        【解决方案3】:

        您可以改用NodeListOf 接口。

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

        【讨论】:

          猜你喜欢
          • 2011-01-24
          • 2018-02-19
          • 2013-03-01
          • 2020-08-29
          • 1970-01-01
          • 2019-02-18
          • 1970-01-01
          • 1970-01-01
          • 2022-07-01
          相关资源
          最近更新 更多