添加 *ngFor 索引值会导致“超出最大调用堆栈大小”

问题描述

StackBlitz demo

我有一个相当简单的视图,它使用 angular 的 html 钩子在 *ngFor 上循环。我使用 ngx-bootstrap collapse 根据内容 .length 显示更多/更少的内容。我遇到的问题是,当我折叠一个多/少按钮时,它们都会折叠/展开。

我已将 let i - index; 添加*ngFor 以索引每个按钮,添加类似 isCollapsed[i]。索引计数正确。

在我的 .ts 文件中,我已像 isCollapsed = true; 一样初始化,但收到以下错误 Cannot create property '1' on boolean 'true'。然后我将其更改为 isCollapsed: boolean[] = [];,然后我收到错误 Maximum call stack size exceeded

这是我的应用程序视图的 stackBlitz - 任何帮助或修复将不胜感激。

解决方法

您必须初始化 isCollapsed

只需添加:

 constructor(){
    this.attributes.map(t=> this.isCollapsed.push(false) );
  }

Here 是工作样本。