user2924127
user2924127

Reputation: 6240

Angular2 click looped item and get it's contents

I have some html which looks like this:

<ion-list>
  <ion-item (click)='handleClick($event, i)' *ngFor="#item of items">
    {{ item }}
  </ion-item>
</ion-list>

I then have a js file which looks like this:

 this.items = [
            'Amsterdam',
            'Bogota',
            'Buenos Aires',
            'Cairo',
            'Dhaka',
            'Edinburgh',
            'Geneva',
            'Genoa',
            'Glasglow',
            'Hanoi',
            'Hong Kong',
            'Islamabad',
            'Istanbul',
            'Jakarta',
            'Kiel',
            'Kyoto',
            'Le Havre',
            'Lebanon',
            'Lhasa',
            'Lima',
            'London',
            'Los Angeles',
            'Madrid',
            'Manila',
            'New York',
            'Olympia',
            'Oslo',
            'Panama City',
            'Peking',
            'Philadelphia',
            'San Francisco',
            'Seoul',
            'Taipeh',
            'Tel Aviv',
            'Tokio',
            'Uelzen',
            'Washington'
        ];

 handleClick(e, i){
        alert(e);
        alert(i);
    }

This produces a list of cities which I great. I know want to click on a city and I want it to alert which city was clicked, but my approach is not working. How can I do this?

Upvotes: 1

Views: 2450

Answers (3)

Mark Rajcok
Mark Rajcok

Reputation: 364697

To be more efficient, I would use one event handler on the parent element, ion-list, and take advantage of event bubbling:

<ion-list (click)='handleClick($event.target.textContent)'>
  <ion-item *ngFor="#item of items">
    {{ item }}
  </ion-item>
</ion-list>


handleClick(city){
  alert(city);
}

I haven't tested this with Ionic, so I don't know if it will work. This Plunker uses <ul> and <li> instead of the Ionic tags.

Upvotes: 2

Pardeep Jain
Pardeep Jain

Reputation: 86750

You are doing right just you have to add the method/function in the typescript file(controller of angular2) and one thing pass item too along with parameters like this:

<ion-list>
  <ion-item (click)='handleClick($event, i, item)' *ngFor="#item of items #i=index">
    {{ item }}
  </ion-item>
</ion-list>

// In the controller part do this

handleClick(event, index, item){
   alert(item);
   console.log(event, item, index);
}
  • No need to pass index(i) if its not required.

Upvotes: 2

micronyks
micronyks

Reputation: 55443

Sorry, I dont know <ion-list> as I don't use Ionic Framework.

Note : I have replaced it with <ul><li>.

  • check demo

    <ul>
      <li (click)='handleClick(item, i)' *ngFor="#item of items;#i = index">
        {{ item }}
      </li>
    </ul>
    
    handleClick(val, i){
            console.log(val + i);
    }
    

    Upvotes: 3

  • Related Questions