How to give IDs to ion-items via ngFor?


#1

I have an array data that I output in a ion-list as individual ion-items:

<ion-list class="showlist">
   <ion-item *ngFor="let show of data" (click)="tapShow($event, show)">
      ...
   </ion-item>
</ion-list>

This works just fine.

But now I need to give each ion-item its own ID attribute in the source code so I can select the list item for automated testing.

How do I best do that?

I tried putting a div inside the ion-item, but this messes with the CSS as Ionic internally creates a few more HTML elements and the div is thrown in the mix pretty random.


#2

let i=index and #i – unless I misunderstand your question. But you can have the ngFor generate the id’s and use them as template id’s that way.


#3

show even has an ID - but how do I apply that to the ion-item as a HTML attribute?


#4

The syntax isn’t exactly extremely intuitive, but you can bind [attr.id].


#5

I haven’t tried this, but I don’t see why it wouldn’t work.

<ion item *ngFor="let s of shows" [id]="s.id">


#6

Heh, I was debating going with that instead of [id] but I think the attr.x syntax is ugly. Do you know a reason to prefer it?


#7

It’s only needed for pure (legacy?) HTML attributes that don’t map to properties. The canonical example in the Angular docs is:

<td [colspan]="n">bummer</td>
<td [attr.colspan]="n">happiness</td>

#8

Thanks, this does work (in principle)!

show is actually of form { title: "foo", ids: { bar: 123 } }.
If I use [attr.id]="show.ids.bar" I get this strange error:

image

When I use [attr.id]="show.title" everything works as expected. Does this make sense to one of you?


#9

Are you using Firefox?


#10

Yes, this is indeed running in Firefox right now. Is this relevant?


#11

It’s a special error. I don’t understand it well, but you probably have a naming problem, like two different things named “bar” and the way the template is parsing gets confused.


#12

Oh indeed it is, the error message makes much more sense in Chrome: “Cannot read property … of undefined”. Which is true, because I initialize this with a “skeleton” array that only has empty entries - that are missing ids.


#13

Oh, ok, even simpler!


#14

What a shitty error message from Firefox - and really unexpected for it to be different from Chrome as well!