Reputation: 6240
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
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
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);
}
Upvotes: 2
Reputation: 55443
Sorry, I dont know <ion-list>
as I don't use Ionic Framework.
Note : I have replaced it with <ul><li>
.
<ul>
<li (click)='handleClick(item, i)' *ngFor="#item of items;#i = index">
{{ item }}
</li>
</ul>
handleClick(val, i){
console.log(val + i);
}
Upvotes: 3