admin管理员组文章数量:1305785
I am using this answer to convert a HTML string to DOM elements in Angular.
The problem is that I can't get attributes of Node
. getAttribute()
cannot be used since typescript will plain that No property getAttribute on Node
.
Code is below (simplified).
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 plained
}
}
}
I am using this answer to convert a HTML string to DOM elements in Angular.
The problem is that I can't get attributes of Node
. getAttribute()
cannot be used since typescript will plain that No property getAttribute on Node
.
Code is below (simplified).
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 plained
}
}
}
Share
Improve this question
edited May 19, 2019 at 16:00
funkid
asked May 19, 2019 at 15:46
funkidfunkid
6652 gold badges12 silver badges31 bronze badges
3 Answers
Reset to default 5TypeScript's view of the API. At the moment there is no way to say that the type of foo.parentNode depends on the type of foo. Currently it is inferred to always be of type Node and Node does not contain the API querySelector (available on Element)
FIX
Use a type assertion as shown:
Instead of:
anchor.getAttribute('href')
Use:
(<Element>anchor).getAttribute('href')
You can use the NodeListOf
interface instead.
const anchorNodes: NodeListOf<HTMLAnchorElement> = template.content.querySelectorAll('a');
const anchors: HTMLAnchorElement[] = Array.from(anchorNodes);
You can set the anchors property as an array of any
const anchors: any[] = Array.from(anchorNodes);
and shouldn't it be Noedlist array as your code refers to that in the previous line-
const anchors: NodeList [] = Array.from(anchorNodes);
本文标签: javascriptHow to get DOM Node attributes in AngularStack Overflow
版权声明:本文标题:javascript - How to get DOM Node attributes in Angular - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741809319a2398696.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论