Angular 2、ngFor每次迭代都创建一个新的上下文?

Angular 2, ngFor create a new context for each iteration?

大家好! 在Angular2中,*ngFor为每次迭代创建一个新的上下文?就像 angular js 中的 ng-repeat 一样?我需要更改 *ngFor 中的一个变量值,但该值会在所有迭代中发生变化。示例:

<div *ngFor="let label of labels">
    <div class="company"><a (click)="isCollapsed = !isCollapsed;isCollapsed ?                       labelStyle = {color: 'gray'}:labelStyle = {color: '#337ab7'}"                       [ngStyle]="labelStyle">{{label}}</a>
     </div>
     <div [ngbCollapse]="isCollapsed">
         <div class="item" *ngFor="let product of products">
            <div class="meta" *ngIf="product.year == label">
              <div class="details">
                <div [innerHTML]=product.reference></div>
              </div>
            </div>
         </div>
      </div>
</div>

当我点击标签时,isCollapsed 从 false 变为 true,但 isCollpsed 在所有迭代中都发生变化。你能给我一个关于只点击并折叠一个标签的建议吗?

谢谢

添加 isCollapsed 作为标签使用的 class 的 属性。

在您的组件中,如果您的 'labels' 是一个数字数组,即如果它当前是:

labels: number[]

然后改成

labels: MyLabel[]

并在您的组件 class 之后添加一个名为 MyLabel 的模型,例如:

class MyLabel{
   constructor(public year: number, public isCollapsed: boolean){}
}

然后在 html 中你可以这样使用它:

<div *ngFor="let label of labels">
<div class="company"><a (click)="label.isCollapsed = !label.isCollapsed                     labelStyle = {color: 'gray'}:labelStyle = {color: '#337ab7'}"                       [ngStyle]="labelStyle">{{label.year}}</a>
 </div>
 <div [ngbCollapse]="label.isCollapsed">
     <div class="item" *ngFor="let product of products">
        <div class="meta" *ngIf="product.year === label.year">
          <div class="details">
            <div [innerHTML]=product.reference></div>
          </div>
        </div>
     </div>
  </div>

您可以在组件中使用 index 名称定义一个字段并将其设置为 null 并使用 $index,如下所示:

<div class="company"><a (click)="toggleCollapsed($index) ? labelStyle = {color: 'gray'}:labelStyle = {color: '#337ab7'}"                       [ngStyle]="labelStyle">{{label.year}}</a>

并定义 toggleCollapsed(index) 如下:

toggleCollapsed(index : number){
    this.index != index ? this.index = index : this.index = null;
    return this.index == index;
}