[英]How to get the Index id in Angular2 typescript
I want to get the html generated id value in typescript ngOnInit().我想在打字稿 ngOnInit() 中获取 html 生成的 id 值。 This is the question for Angular2 Here is the scenario.这是 Angular2 的问题 这是场景。
<html>
<div *ngFor='let post of data; let i = index' [attr.data-index]="i">
<button id="cdata_{{i}}">Click<button>
//here id will generate for the button in loop
</div>
</html>
Now in typescript (.ts) file现在在打字稿(.ts)文件中
ngOnInit(){
//How to get the index value here in this function?Without any click function in html.
}
I have to write that onInit.this should load on the page load.我必须写上 onInit.this 应该在页面加载时加载。 The id which i generated,is showing on the Html page but,i want the get those id to perform some operation in typescript>ngOnInit
.我生成的 id 显示在 Html 页面上,但是,我希望获取这些 id 在typescript>ngOnInit
执行一些操作。
in ngOnInit(){}
,this should be something like this=> this.service.x.subscribe(data=>{ var indexK=document.getElementById("cdata_"+i); console.log("indexK"); })
在ngOnInit(){}
,这应该是这样的=> this.service.x.subscribe(data=>{ var indexK=document.getElementById("cdata_"+i); console.log("indexK"); })
This one is not working.This should be print like这个不起作用。这应该像打印一样
cdata_0
cdata_1
cdata_2
cdata_3
If you want to reach the DOM you cannot get elements by id from ngOnInit because there is no DOM loaded yet.如果你想访问 DOM,你不能通过 ngOnInit 的 id 获取元素,因为还没有加载 DOM。 You need to call your function like this (or you can use observable)你需要像这样调用你的函数(或者你可以使用 observable)
ngAfterContentInit(){
data.forEach((item, index) => {
var indexK=document.getElementById("cdata_"+index);
console.log("indexK");
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.