我在循环中有一个元素,我只想更改它的 id 以避免冲突。我做了一些搜索,但似乎找不到任何东西。
<div *ngFor="let location of job.tasks; let i = index">
<div id="index-{{i}}">
{{index}}
</div>
</div>
问题是当我调用 ngOnInit 时document.getElementById('index-1')
它返回 null,因为它还没有分配 id。
连接ngFor
index(i
) 里面id
属性。
<div *ngFor="let location of job.tasks; let i = index">
<div id="index-{{i}}">
{{index}}
</div>
</div>
你应该查询你的 DOMngFor
循环结束,你可以在里面做同样的事情ngAfterViewInit
生命周期事件
ngAfterViewInit(){
console.log(document.getElementById('1'));
}
演示在这里 https://plnkr.co/edit/dFy18Z0hObzCWfsad70A?p=preview
使用更正确的方法来做到这一点#template-variable
on ngFor
模板和@ViewChildren
装饰器找出各自的 DOM。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)