Dynamically assign element id inside 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>
It works and creates the div
with the correct id
document.getElementById("wave1")
Output will be like this:
<div id="wave1">wave1</div>
but remember your code will start from wave0
as i = index
starts from 0.
What you have is correct and should work in angular 4/5. Are you maybe using a really old, pre-release angular 2 version?
Here is a stackblitz with your code and the code below, both working
https://stackblitz.com/edit/angular-khur4v?file=app%2Fapp.component.html
You can also do it that way, which is the preferred way
<li *ngFor="let episode of episodes; let i = index"> <div [attr.id]="'wave' + i">{{episode.name}}</div></li>
You don't need to define i
<li *ngFor="let episode of episodes"> <div id="wave{{episode}}">{{episode}}</div></li>
EDIT: in case episodes is a list of objects
<li *ngFor="let episode of episodes"> <div id="wave{{episodes.indexOf(episode)}}">{{episode.name}}</div></li>