简体   繁体   English

在 *ngFor 的每次迭代中只调用一次函数

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

I have this code, with which a *ngFor calls a function ( randomData(i) ) many times in the same iteration.我有这个代码, *ngFor在同一次迭代中多次调用函数( randomData(i) )。

<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.也许将randomData(i)的值存储在模板中的临时变量中,或者避免多次运行该函数。

process your data in your ts file like this:像这样处理 ts 文件中的data

data.forEach((item, i) => {
      item = Object.assign(item, this.randomData(i));
});

Then update your template:replace all the randomData(i) with item然后更新你的模板:用item替换所有的randomData(i)

<div class="col-sm-12">
   <ng-container *ngFor="let item of data; let i = index">
     <div
        [ngClass]="{
        'd-none':
            item.clase == 'categoria1' && !categoria1) ||
            item.clase == 'categoria2' && !categoria2) ||
            item.clase == 'categoria3' && !categoria3)
        }">
        <div id="ribbon-container">
        <span id="ribbon" [ngClass]="item.clase">
          {{item.categoria}}
        </span>
        </div>
        <div>
        <img [src]="'./assets/img/emotions/' + item.imagen" class="img-fluid imagen_tarjeta_emociones float-right"
        />
    </div>
 </ng-container>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM