【问题标题】:How do you dynamically change the id of an element in Angular?如何动态更改 Angular 中元素的 id?
【发布时间】:2018-02-23 12:38:29
【问题描述】:

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

【问题讨论】:

    标签: angular element


    【解决方案1】:

    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 模板和@ViewChildren 装饰器上使用#template-variable 来查找相应的DOM 的更正确方法。

    【讨论】:

    • 这行得通,但我意识到问题不是我想的那样。我更新了我的问题以反映我的错误。
    猜你喜欢
    • 1970-01-01
    • 2014-12-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-27
    • 2011-05-03
    • 2017-02-01
    • 2015-09-01
    相关资源
    最近更新 更多