Angular *ngFor 在地图上 运行ning 多次但应该只 运行 一次

Angular *ngFor over a map is running multiple times but should only run once

Stackblitz Demo of my app

在我的应用程序中,我尝试遍历地图(使用 *ngFor)并在新的扩展面板中显示每个地图键,并在扩展面板的“正文”中显示值:

地图以字符串作为键,以字符串数组作为值。填满地图后,我将其传递到 this.showMap。这样做的唯一原因是我可以在我的 HTML 中等待 showMap*ngIf="showMap" 以确保在向用户显示网站之前所有项目都在地图中:

  showMap: any;

  ngOnInit() {
    let myMap: Map<string, string[]> = new Map<string, string[]>();
    myMap.set("food", ["apple", "sausage"]);
    myMap.set("money", ["bitcoin", "dollar"]);
    //... add more key, value pairs dynamically
    this.showMap = myMap;
  }

在我的 HTML 中,我使用 accordionexpansion-panels 来自 material:

 <div *ngIf="showMap">

    <mat-accordion>
      <mat-expansion-panel hideToggle *ngFor="let key of getKeys(showMap); index as i">
        <mat-expansion-panel-header>
          <mat-panel-title>
            {{ key }}
          </mat-panel-title>
        </mat-expansion-panel-header>
        <p>{{ getValues(showMap)[i] }}</p>
      </mat-expansion-panel>
    </mat-accordion>
  </div>

getKeys()getValues() 函数看起来像这样 return showMap:

的键和值
getKeys(myMap: Map<string, string[]>) {
    let keys = Array.from(myMap.keys());
    console.log("keys: ", keys);
    return keys;
  }

  getValues(myMap: Map<string, string[]>) {
    let values = Array.from(myMap.values());
    console.log("values: ", values);
    return values;
  }

我的应用程序是 运行,但在控制台日志中我看到函数 getKeys()getValues() 被多次调用。我希望 getKeys() 被调用一次(因为 *ngFor 语句)并且 getValues() 被调用两次(每个键一次)。但它更多,大约 10 倍?:

正如@Raz Ronen 所提到的,在模板上调用函数并不是一个好的做法,每次运行 Angular 变化检测时都会执行函数。那可能太多次了!我会将值和键提取到实例变量中并使用它们,而不是直接在模板上调用函数。

看看这篇关于它的文章:https://medium.com/showpad-engineering/why-you-should-never-use-function-calls-in-angular-template-expressions-e1a50f9c0496