Amal
Amal

Reputation: 75

Change image on click using Angular2

I'm trying to change the heart image of the list when I click on it but every time I click all the other heart images of the list change also.

here is a screen shoot of my list :

enter image description here

and here is the html list :

<ul class="list-group">
  <li 
    class="list-group-item" 
    *ngFor="let film of items">
    {{film.text}}
    <img 
      [src]="imgSrc" 
      (click)="fav(film.text)" 
      class="heart">
    <img 
      (click)="delete(film.text)" 
      class="deletebtn" 
      src="/assets/images/delete.png">
  </li>
</ul>

and the function in the component:

imgSrc: string = "../../assets/images/heartnotclicked.png";
wasClicked = false;

fav(film) {
  if (this.wasClicked === false) {
    this.wasClicked = true;
    this._filmService.addFavFilms(film);
    this.imgSrc = "../../assets/images/heart.png";
  } else {
    this.wasClicked = false;
    console.log(this.wasClicked);
    this._filmService.deleteFav(film.text);
    this.imgSrc = "../../assets/images/heartnotclicked.png";
  }
}

Upvotes: 0

Views: 1598

Answers (1)

Suresh Kumar Ariya
Suresh Kumar Ariya

Reputation: 9764

The Image src & wasClicked property should be part of film object i.e film.imgSrc, which will update the particular row. Currently you are maintaining one property which will update all items.

<ul class="list-group">
    <li class="list-group-item" *ngFor="let film of items" >{{film.text}}
        <img [src]="film.imgSrc" (click)="fav(film)" class="heart"> 
        <img (click)="delete(film.text)" class="deletebtn"src="/assets/images/delete.png">
    </li>
</ul>

Component:

imgSrc: string = "../../assets/images/heartnotclicked.png";
wasClicked = false;
fav(film){
  if(film.wasClicked === false){
    film.wasClicked = true;
    this._filmService.addFavFilms(film);
    film.imgSrc = "../../assets/images/heart.png";   
  }
  else {
    film.wasClicked = false;
    console.log(film.wasClicked);
    this._filmService.deleteFav(film.text);
    film.imgSrc = "../../assets/images/heartnotclicked.png";
  }
}

Upvotes: 2

Related Questions