Hi Im trying to do this in an html template in angular. It shows the icon I want, but the function gets called like much to often... what am I missing here? Template
<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>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
getIcon(id: string): string {
const iconName = this[id];
console.log(iconName);
return iconName;
}
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
Console output: (why?)
CodePudding user response:
There is nothing wrong with your code. The getIcon()
function is being called so many times because of the way Angular works. The property bindings []
are evaluated at every change detection cycle.
See this question here to get a full explanation.
But you can optimize it binding to a property instead a function, which is the recommended way of binding properties.
For example, in your case, if you know what are the possible icon classes, you can do something like:
// component.ts
const icons = {
1: 'dog',
2: 'cat'
}
<!-- component.html -->
...
<fa-icon [icon]="icons[pet.type]"></fa-icon>
...