Ionic 4 Getting ion-item ID or Assigning id/value to ID

#1

Hi,

I am trying to find a way to get the id of an ion-item when the item is clicked or assign an id to the ion-item. I want to use the ID to display the correct picture on another page. Therefore, I won’t have to add an extra forty pages to my application.

list-buildings.page. html- this is where I need to assign or get the ID of the item

 <ion-item>
            <img src = "/assets/img/gym.jpg" (click) = "goToFunBuildings()">
            <ion-label color = "light" text-wrap text-right>Campus Gym!</ion-label>
        </ion-item>

funbuildings-page.page.ts- this is where I will be using the ID to display the correct image of the buildings

#2

can you post the corresponding typescript?

you should be able to use the *ngFor directive to loop over the list for each <ion-item> and pass the index to the goToFunBuildings() method

ex

<ion-item *ngFor="let building of buildingList">
    <img [src]="building.image" (click)="goToFunBuildings(building.id)">
<ion-label>{{ building.label }}</ion-label>
</ion-item>

with an array of custom “building” Objects in the typescript like this

public buildingList: any[] = [
    {
        id: 1,
        label: 'Campus Gym!',
        image: '/assets/img/gym.png',
        .... //any other properties
    }
    ..... //rest of buildings
];

Hope this can help you!

1 Like
#3

Thank you so much, this really helped me out a lot. Now, all I have to do is figure out how to reference ID in the fun buildings ts file

#4
goToFunBuildings(id: number) {
    let selected building = this.buildingList.filter((building) => building.id === id)[0];
#5

Can you explain to me what this is doing, because I am getting an error? Thank you!

#6

Array.filter

The filter function iterates through the array and returns the element if the inner function evaluates to true. And the [0] should return the first value, assuming all the ids are unique there should only be 1 item in the array

Can you post the error?

#7

building is underline with the error:

,’ expected.ts(1005) let building: any

#8

Oops I see the problem
Autocorrect on mobile added a space

let selectedBuilding: any
#9

I’m sorry I am still so confused, this is my first time using Ionic.

I added the following in list-building ts file

goToFunBuildings(id: number) {
let selectedBuilding: any = this.buildingList.filter((building) => building.id === id)[0]; }

However, in trying to reference id in fun buildings ts file to display the correct image based on id, it doesn’t work.

 if(selectedBuilding == 1){
      this.angularLogo= "/assets/img/gym.jpg";
    }
#10

You could try setting the img src to

[src]="selectedBuilding?.image"

And have a global selectedBuilding variable instead and use this.selectedBuilding instead of let

#11

Or if you have this.angularLogo you can do

this.angularLogo = selectedBuilding.image