Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically assign element id inside ngFor

Tags:

angular

ngfor

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.

like image 941
Tom O'Brien Avatar asked Mar 31 '18 16:03

Tom O'Brien


1 Answers

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.

like image 54
Hend Khalifa Avatar answered Sep 19 '22 07:09

Hend Khalifa