【发布时间】: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