简体   繁体   English

TypeScript-类型“节点”上不存在属性“ id”

[英]TypeScript - Property 'id' does not exist on type 'Node'

I got this issue working with TypeScript (for Angular2) when I try to get the id of an element. 当我尝试获取元素的ID时,遇到了使用TypeScript(针对Angular2)的问题。 See this example: 请参阅以下示例:

<div id="search">
    <div id="field1"></div>
    <div id="field2"></div>
</div>

If I try to get the id of one of the nested div, I can do this normally: 如果我尝试获取嵌套div之一的ID,则可以正常执行此操作:

var element = document.getElementById("search");
var subelement = element.childNodes;
subelement[1].id;

Then I will have "field2". 然后,我将获得“ field2”。

However when I try to do this with TypeScript I got the message Property 'id' does not exist on type 'Node'. 但是,当我尝试使用TypeScript执行此操作时,我收到消息“ 属性”“ id”在类型“节点”上不存在。 And as result my code doesn't work. 结果我的代码不起作用。 I really need a solution for this since I need to know the nested elements inside another, unless there are a better way. 我真的需要一个解决方案,因为除非有更好的方法,否则我需要了解另一个内部的嵌套元素。

Nodes can be more than just elements and don't necessarily have an id property. 节点不仅可以是元素,而且不一定具有id属性。 You should use .children which is a collection of elements only. 您应该使用.children ,它仅是元素的集合。

error TS2551: Property 'setAttribute' does not exist on type 'Node'. 错误TS2551:类型“节点”上不存在属性“ setAttribute”。 Did you mean 'attributes'? 您是说“属性”吗?

const elements = document.querySelectorAll("text");

elements[k].style.transform = '...........'; ////error ////错误

elements[k]['style'].transform = '..........'; //is working //正在工作

elements[k].parentNode.setAttribute('....'); ////error ////错误

elements[k].parentNode['setAttribute']('..'); //is working //正在工作

I would use document.getElementById to reference a DOM element in Angular2 but rather leverages @ViewChild like this: 我会使用document.getElementById来引用Angular2中的DOM元素,而是像这样利用@ViewChild

@Component({
  (...)
  template: `
    <div #search>
      <div id="field1"></div>
      <div id="field2"></div>
    </div>
  `
})
export class SomeComponent {
  @ViewChild('search') searchElement:ElementRef;

  ngAfterViewInit() {
    let domElement = searchElement.nativeElement;
    (...)
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM