angular - 更改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
,所以当它发生变化时,它应该刷新页面,但这不起作用。
解决方案
您应该像这样更新 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 setter
在imgSrc
每次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);
}
推荐阅读
- android - Android-Keyboard 随机显示 onResume
- assembly - MOV 从内存中注册不能在 nasm 中使用 BITS 32
- mongodb - 如何同时高效地将数据写入 NoSQL 和 RDBMS
- javascript - jQuery 代码没有运行 $(function(){...}); 但没有它会运行
- php - PHP POST 未填写
- php - 在 Woocommerce 客户处理和完成的电子邮件通知中更改文本
- java - Spring boot - 休眠配置问题(创建名称为“entityManagerFactory”的bean时出错)
- python - 通过遍历键列表并与另一个字典配对来使用键值对填充字典
- python - 为什么 django 中的实例对我不起作用?
- common-lisp - SBCL 上的 USocket:连接被拒绝(Drakma 和 Dex)