I have this code, with which a *ngFor
calls a function (randomData(i)
) many times in the same iteration.
<div class="col-sm-12">
<ng-container *ngFor="let item of data; let i = index">
<div
[ngClass]="{
'd-none':
(randomColor(i).clase == 'categoria1' && !categoria1) ||
(randomColor(i).clase == 'categoria2' && !categoria2) ||
(randomColor(i).clase == 'categoria3' && !categoria3)
}">
<div id="ribbon-container">
<span id="ribbon" [ngClass]="randomColor(i).clase">
{{randomColor(i).categoria}}
</span>
</div>
<div>
<img [src]="'./assets/img/emotions/' + randomColor(i).imagen" class="img-fluid imagen_tarjeta_emociones float-right"
/>
</div>
</ng-container>
randomData(i) {
if (i == 0) {
return {
categoria: "Categoría 1",
clase: "categoria1",
imagen: "Alegria.png",
};
} else if (i % 2) {
return {
categoria: "Categoría 2",
clase: "categoria2",
imagen: "Enfado.png",
};
} else if (i % 3) {
return {
categoria: "Categoría 3",
clase: "categoria3",
imagen: "Neutro.png",
};
}
}
Is there a way that this function is only called once for each iteration? maybe store the value of randomData(i)
in a temporary variable in the template or something to avoid running the function so many times.