如何动态更改 Angular 中元素的 id?

How do you dynamically change the id of an element in Angular?

我有一个循环中的元素,我只想更改它的 ID 以避免冲突。我做了一些搜索,但似乎找不到任何东西。

<div *ngFor="let location of job.tasks; let i = index">
  <div id="index-{{i}}">
    {{index}}
  </div>
</div>

问题是当我调用 ngOnInit document.getElementById('index-1') 它 returns null 因为它还没有分配 id。

id 属性内连接 ngFor 索引 (i)。

<div *ngFor="let location of job.tasks; let i = index">
  <div id="index-{{i}}">
    {{index}}
  </div>
</div>

你应该查询你的 DOM ngFor 循环,你可以在 ngAfterViewInit 生命周期事件

中做同样的事情
ngAfterViewInit(){
    console.log(document.getElementById('1'));
}

Demo Here


更正确的方法是在 ngFor 模板上使用 #template-variable@ViewChildren 装饰器来找出各自的 DOM.