【问题标题】:Ionic change image on click?点击时离子改变图像?
【发布时间】:2020-10-15 17:58:08
【问题描述】:

我想在单击按钮时更改图像。

我做了这个:

home.html

 

还有我的家.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",
      },
    ];
  }
}

但这是我能做到的。

【问题讨论】:

  • 你的卡片变量是一个数组,你打算显示多张图片还是只显示一张?

标签: html typescript image ionic-framework ionic4


【解决方案1】:

问题出在<img [src]="cards.img" />。您正在尝试读取数组的.img,而不是单个卡。

在你的类上有一个selectedCardIndex 变量,点击按钮时,你需要设置 selectedCardIndex 值。

您可以将代码更改为以下代码以使其正常工作:

<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;
    }
  }
}

【讨论】:

    猜你喜欢
    • 2016-09-27
    • 2014-04-29
    • 1970-01-01
    • 1970-01-01
    • 2019-07-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多