简体   繁体   中英

How to get the Index id in Angular2 typescript

I want to get the html generated id value in typescript ngOnInit(). This is the question for Angular2 Here is the scenario.

<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

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. 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 .

in ngOnInit(){} ,this should be something like this=> 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. You need to call your function like this (or you can use observable)

ngAfterContentInit(){
 data.forEach((item, index) => {
    var indexK=document.getElementById("cdata_"+index); 
    console.log("indexK");
  });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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