Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/363.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何在Angular中获取DOM节点属性_Javascript_Angular_Typescript_Dom - Fatal编程技术网

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

Javascript 如何在Angular中获取DOM节点属性,javascript,angular,typescript,dom,Javascript,Angular,Typescript,Dom,我正在使用它将HTML字符串转换为Angular中的DOM元素 问题是我无法获取节点的属性getAttribute(),因为typescript会抱怨节点上没有属性getAttribute 代码如下(简化) 从'@angular/core'导入{AfterViewInit,Renderer2}; 导出类MockComponent实现AfterViewInit{ 构造函数(私有呈现器:Renderer2){} 私有模拟字符串=“” ngAfterViewInit():void{ const tem

我正在使用它将HTML字符串转换为Angular中的DOM元素

问题是我无法获取
节点
的属性<无法使用代码>getAttribute(),因为typescript会抱怨节点上没有属性getAttribute

代码如下(简化)

从'@angular/core'导入{AfterViewInit,Renderer2};
导出类MockComponent实现AfterViewInit{
构造函数(私有呈现器:Renderer2){}
私有模拟字符串=“”
ngAfterViewInit():void{
const template=this.renderer.createElement('template');
template.innerHTML=this.mockString.trim();
常量固定节点:NodeList=template.content.querySelectorAll('a');
常量锚点:节点[]=数组。从(锚点节点);
用于(锚的常数锚){
//如何在这里获取锚的属性?
//将投诉anchor.getAttribute('href')
}
}
}

您可以将anchors属性设置为任意

const anchors: any[] = Array.from(anchorNodes);
它不应该是Noedlist数组,因为您的代码引用了前一行中的数组-

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

TypeScript的API视图。目前无法确定foo.parentNode的类型取决于foo的类型。当前,它被推断为始终为Node类型,并且Node不包含API querySelector(在元素上可用)

修复

使用类型断言,如图所示:

而不是:

anchor.getAttribute('href')
使用:

(anchor.getAttribute('href'))

您可以改用
NodeListOf
界面

const anchorNodes: NodeListOf<HTMLAnchorElement> = template.content.querySelectorAll('a');
const anchors: HTMLAnchorElement[] = Array.from(anchorNodes);
常量固定节点:NodeListOf=template.content.querySelectorAll('a'); 常量锚点:htmlanchoreElement[]=Array.from(锚点节点);
const anchorNodes: NodeListOf<HTMLAnchorElement> = template.content.querySelectorAll('a');
const anchors: HTMLAnchorElement[] = Array.from(anchorNodes);