嗨,我正试着在angular的html模板中做到这一点。它显示了我想要的图标,但该函数的调用方式与通常情况下非常相似。这里我漏掉了什么?模板
<li class="pet-list__entry" *ngFor="let pet of listOfPets">
<div class="pet-list__entry__image-segment">
<fa-icon [icon]=getIcon(pet.type)></fa-icon>
</div>
<div class="pet-list__entry__data-segment">
{{ pet.name }}
</div>
</li>
getIcon(id: string): string {
const iconName = this[id];
console.log(iconName);
return iconName;
}控制台输出:(为什么?)

发布于 2021-11-02 02:08:23
您的代码没有任何问题。由于Angular的工作方式,getIcon()函数被调用了很多次。属性绑定[]在每个变更检测周期都会被评估。
请参阅this question here以获得完整的解释。
但您可以将其优化为绑定到属性而不是函数,这是绑定属性的推荐方式。
例如,在您的示例中,如果您知道可能的图标类是什么,则可以执行以下操作:
// component.ts
const icons = {
1: 'dog',
2: 'cat'
}<!-- component.html -->
...
<fa-icon [icon]="icons[pet.type]"></fa-icon>
...https://stackoverflow.com/questions/69804051
复制相似问题