Dynamically assign element id inside ngFor
Asked Answered
Y

4

36

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.

Yokefellow answered 31/3, 2018 at 16:0 Comment(4)
Can you add code where you use '#wave...? Seems it's clear that you concat object with stringNunnally
which version of angular are you using?Landre
https://mcmap.net/q/217387/-how-to-set-dynamic-id-in-ngfor, https://mcmap.net/q/425315/-give-dynamic-id-angular2-bindsBegum
angular 2 is the versionSlily
G
42

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.

Geter answered 31/3, 2018 at 16:26 Comment(1)
That's great for assigning the id, but how do you then reference the Id dynamically in your html? I am trying to implement validation against a field with a dynamically assigned Id. I need to be able to say something like *ngIf="'controlName' + index.invalid".Damper
L
13

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>
Landre answered 31/3, 2018 at 16:24 Comment(0)
S
5

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>
Strobila answered 31/3, 2018 at 16:5 Comment(2)
That won't work if episodes is a list of objects, which it probably is in the OP's exampleLandre
True, let me modify the exampleStrobila
A
2

For me it works if I add Singlequotes. Otherwise Angular detects a var.

<li *ngFor="let episode of episodes; let i = index">
    <div id="'wave' + i"></div>
</li>
Agential answered 31/3, 2018 at 16:14 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.