本文介绍了在ngFor内部动态分配元素ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试为* ngFor中的div提供一个动态分配的ID.我希望将div称为"wave1,wave2,wave3"等.
I'm trying to give a dynamically assigned id for a div inside a *ngFor. I would like the divs to be called 'wave1, wave2, wave3' etc.
<li *ngFor="let episode of episodes; let i = index">
<div id="wave{{i}}"></div>
</li>
但是,这将引发以下错误:
However, this throws the following error:
ERROR DOMException: Failed to execute 'querySelector' on 'Document':
'#wave[object Object]' is not a valid selector.
推荐答案
您可以使用{{ 'wave' + i }}
代替wave{{i}}
.将其设置为Angular Experession.这是完整的ngFor
:
You can use {{ 'wave' + i }}
instead of wave{{i}}
. Make it as Angular Experession. This is the full ngFor
:
<li *ngFor="let episode of episodes; let i = index">
<div id="{{ 'wave' + i }}"></div>
</li>
它可以工作并使用正确的id
It works and creates the div
with the correct id
document.getElementById("wave1")
输出将如下所示:
<div id="wave1">wave1</div>
但是请记住,您的代码将从wave0
开始,而i = index
从0开始.
but remember your code will start from wave0
as i = index
starts from 0.
这篇关于在ngFor内部动态分配元素ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!