Home:ALL Converter>call a function only once in each iteration of an *ngFor

call a function only once in each iteration of an *ngFor

Ask Time:2020-08-28T08:27:12         Author:yavg

Json Formatter

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.

Author:yavg,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/63625825/call-a-function-only-once-in-each-iteration-of-an-ngfor
yy