Clicking any button firing other buttons on ion-list

I’m trying to toggle button to add an item, feed here, to favorite list. the problem here when i click on any button other buttons are fired in the same time? is there a way to stop this behavior?!
this is my code

Template

<ion-content padding>
  <ion-searchbar (ionInput)="getItems($event)"></ion-searchbar>
  <ion-list>
    <ion-list-header>
      <h2>News</h2>
    </ion-list-header>
    <ion-item *ngFor=" let feed of feeds; let i = index " (click)="onFeedSelected(feed)">
      <ion-avatar item-left>
        <img src="{{feed.img}}">
      </ion-avatar>
      <h2>{{ feed.title }}</h2>
      <button ion-button [color]="isMyFav ? 'secondary' : 'primary'" outline text-center icon-right item-right (click)="addToFavList($event, feed)">
        <ion-icon [name]="isMyFav ? 'checkmark' : 'add' "></ion-icon>
          </button>
    </ion-item>
  </ion-list>
</ion-content>

Component

export class HomePage {
  feeds: Feed[] = [];
  myFavList: Feed[] = [];
  isMyFav = false;

  constructor(public navCtrl: NavController, private feedService: FeedService) {
  }

  ionViewDidLoad() {
    this.feeds = this.feedService.loadFeed();
  }
  onFeedSelected(feed: Feed) {
    this.navCtrl.push(FeedListPage, feed);
  }
  addToFavList($event, feed) {
    $event.stopPropagation();
    $event.preventDefault();

    let index = this.feeds.indexOf(feed);
    console.log(index);
    if (!this.isMyFav) {
      if (this.myFavList.indexOf(feed) == -1) {
        this.myFavList.push(feed);
        this.isMyFav = true;
      }
    } else {
      if (this.myFavList.indexOf(feed) != -1) {
        this.myFavList.splice(index, 1);
        this.isMyFav = false;
      }

    }
    console.log(this.myFavList);
  }

}


Hi, you made the entire item clickable. Hence when clicking the button inside it, the other handler is fired as well. To prevent this behavior, prevent the propagation on the click handler from the ion-item (onFeedSelected) or just don’t attach a click handler to the entire thing and then also one inside the item.

2 Likes

thanks for response. sorry for that… if i don’t attach click handlers to the entire thing, I tried to do it but nothing changed!

I have a sneaking suspicion that we’re looking in the wrong place. It may not be about the buttons at all, but rather about the fact that isMyFav is a single boolean shared amongst all feeds. It should instead be a per-feed property, referenced as feed.isMyFav in the template.

1 Like

You’ve two problems, the first one you’ve mentioned yourself and is easy to tackle. Do it like this:

Inside the addToFavList($event, feed) method, call e.stopPropagation() so that the event doesn’t percolate up to the ion-item level.

The second is a logical problem as @rapropos has mentioned, you’ve to give every feed its own isMyFav boolean else every button will change whenever isMyFav is set to true.