[英]How to get the Index id in Angular2 typescript
我想在打字稿 ngOnInit() 中獲取 html 生成的 id 值。 這是 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>
現在在打字稿(.ts)文件中
ngOnInit(){
//How to get the index value here in this function?Without any click function in html.
}
我必須寫上 onInit.this 應該在頁面加載時加載。 我生成的 id 顯示在 Html 頁面上,但是,我希望獲取這些 id 在typescript>ngOnInit
執行一些操作。
在ngOnInit(){}
,這應該是這樣的=> this.service.x.subscribe(data=>{ var indexK=document.getElementById("cdata_"+i); console.log("indexK"); })
這個不起作用。這應該像打印一樣
cdata_0
cdata_1
cdata_2
cdata_3
如果你想訪問 DOM,你不能通過 ngOnInit 的 id 獲取元素,因為還沒有加載 DOM。 你需要像這樣調用你的函數(或者你可以使用 observable)
ngAfterContentInit(){
data.forEach((item, index) => {
var indexK=document.getElementById("cdata_"+index);
console.log("indexK");
});
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.