首页 > 解决方案 > 更改ts文件中的值后图像不会改变

问题描述

我有一个模型,它有一个枚举作为它的属性之一。我想相应地显示图像,因此,如果属性 ( Category) 是音乐,例如,我想显示音乐图像。

这是我的.ts文件:

export class GoalCardComponent implements OnInit {

  @Input() goal: Goal;
  private iconName: string = "default";
  imgSrc: string = `/assets/category-icons/${this.iconName}.png`;

  private categories: string[] = Object.values(Category);
  constructor() { }

  ngOnInit() {
    if(this.goal.category != null && this.categories.includes(this.goal.category)) {
        this.iconName = this.goal.category
    }
  }

}

我将 my 设置iconName为默认值,以防我没有类别属性(它在模型中是可选的)。

问题是我的.html文件不会相应更改,default.png尽管我确实选择了一个类别,但它仍然存在。

这是我的.html文件:

<ion-card>
  <ion-row class="goal-card-container">
      <ion-avatar class="goal-card-category-img" style="background-color: aquamarine; display: flex; justify-content: center; align-items: center;">
        <ion-img [src]="imgSrc" style="width: 90%; height: 90%;"></ion-img>
      </ion-avatar>
      <div class="goal-info-container">
        <ion-label class="goal-title-name">{{ goal.title }}</ion-label>
      </div>

      <a class="details-button"></a>
  </ion-row>
</ion-card>

我的猜测是iconName只有在页面已经显示后才会更新,但我认为[src]应该将源绑定到imgSrc,所以当它发生变化时,它应该刷新页面,但这不起作用。

标签: angularionic-framework

解决方案


您应该像这样更新 ngOnInit 上的 imgSrc:

export class GoalCardComponent implements OnInit {

  @Input() goal: Goal;
  private iconName: string = "default";
  imgSrc: string = `/assets/category-icons/${this.iconName}.png`;

  private categories: string[] = Object.values(Category);
  constructor() { }

  ngOnInit() {
    if(this.goal.category != null && this.categories.includes(this.goal.category)) {
        this.iconName = this.goal.category;
        this.imgSrc = `/assets/category-icons/${this.iconName}.png`;
    }
  }

}

或者,您可以使用目标getter and setterimgSrc每次goal值更改时更新,这将是一个更强大的解决方案:

export class GoalCardComponent implements OnInit {

  @Input() 
  set goal(goal: Goal) {
      this.goal = goal;
      if(this.goal.category != null && this.categories.includes(this.goal.category)) {
        this.iconName = this.goal.category;
        this.imgSrc = `/assets/category-icons/${this.iconName}.png`;
      }
  }

  private iconName: string = "default";
  private _goal: Goal;

  imgSrc: string = `/assets/category-icons/${this.iconName}.png`;

  private categories: string[] = Object.values(Category);

}

推荐阅读