Dynamically assign element id inside ngFor

Tom O'Brien picture Tom O'Brien · Mar 31, 2018 · Viewed 35.8k times · Source

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.

Answer

Hend Khalifa picture Hend Khalifa · Mar 31, 2018

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.