Search code examples
htmltypescriptimageionic-frameworkionic4

Ionic change image on click?


I would like to change an image when I click on a button.

I made this:

home.html

  <div class="card">
    <img [src]="cards.img" />
  </div>
    <ion-button (click)="logEvent($event)">
      <ion-icon slot="icon-only" name="checkmark-outline"></ion-icon>
    </ion-button>
</ion-content>

and my home.ts

export class HomePage implements OnInit {
  cards;
  constructor() {
    this.cards = [];
  }

  ngOnInit() {}

  logEvent(event) {

    console.log("click");

    this.cards = [
      {
        img: "https://placeimg.com/300/300/people",
      },
      {
        img: "https://placeimg.com/300/300/animals",
      },
    ];
  }
}

but that's as far as I can go.


Solution

  • The problem is here <img [src]="cards.img" />. You are trying to read .img of an array, instead of a single card.

    Have a selectedCardIndex variable on your class and on button click, you need to set the selectedCardIndex value.

    You can change your code to below to make it work:

    <div class="card">
      <img [src]="cards[selectedCardIndex].img" />
    </div>
    <ion-button (click)="logEvent($event)">
      <ion-icon slot="icon-only" name="checkmark-outline"></ion-icon>
    </ion-button>
    
    export class HomePage implements OnInit {
      cards;
      selectedCardIndex = 0;
    
      constructor() {
        this.cards = [
          {
            img: "https://placeimg.com/300/300/people",
          },
          {
            img: "https://placeimg.com/300/300/animals",
          },
        ];
      }
    
      ngOnInit() {}
    
      logEvent(event) {
        const newIndex = this.selectedCardIndex + 1;
        
        if (newIndex === this.cards.length) {
          this.selectedCardIndex = 0;
        } else {
          this.selectedCardIndex = newIndex;
        }
      }
    }