如何在Angular中动态更改元素的ID? [英] How do you dynamically change the id of an element in Angular?

查看:747
本文介绍了如何在Angular中动态更改元素的ID?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在一个循环中有一个元素,我只想更改它的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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆