如何在Angular中动态更改元素的ID? [英] How do you dynamically change the id of an element in Angular?
问题描述
我在一个循环中有一个元素,我只想更改它的id以避免冲突.我做了一些搜索,但似乎找不到任何东西.
I have an element in a loop and I just want to change it's id so as to avoid conflicts. I did some searching, but can't seem to find anything.
<div *ngFor="let location of job.tasks; let i = index">
<div id="index-{{i}}">
{{index}}
</div>
</div>
问题是当我在ngOnInit document.getElementById('index-1')
中调用时,它返回null,因为它尚未分配ID.
The problem is when I call in ngOnInit document.getElementById('index-1')
it returns null because it hasn't assigned the id yet.
推荐答案
在id
属性内连接ngFor
索引(i
).
Concatenate ngFor
index(i
) inside id
attribute.
<div *ngFor="let location of job.tasks; let i = index">
<div id="index-{{i}}">
{{index}}
</div>
</div>
您应该查询DOM ngFor
循环遍历,您可以在ngAfterViewInit
生命周期事件中执行相同的操作
You should query your DOM ngFor
looping over, you can do the same inside ngAfterViewInit
lifecycle event
ngAfterViewInit(){
console.log(document.getElementById('1'));
}
使用ngFor
模板上的#template-variable
和@ViewChildren
装饰器查找相应的DOM的更正确方法.
More right way to do this using #template-variable
on ngFor
template and @ViewChildren
decorator to find out respective DOM.
这篇关于如何在Angular中动态更改元素的ID?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!