Home:ALL Converter>Angular 2, ngFor create a new context for each iteration?

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

Ask Time:2017-05-16T03:15:34         Author:Jhonatan Alarcon

Json Formatter

Everyone! In Angular 2, *ngFor create a new context for each iteration? like ng-repeat in angular js?. I need to change a variable value inside *ngFor, but that value change for all iterations. Example:

<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>

Author:Jhonatan Alarcon,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/43987183/angular-2-ngfor-create-a-new-context-for-each-iteration
Jainam Jhaveri :

add isCollapsed as a property of class used by labels.\n\nIn your component, if your 'labels' is a number array, i.e. if it is currently:\n\nlabels: number[]\n\n\nthen change it to \n\nlabels: MyLabel[]\n\n\nand after your component class add a model called MyLabel like:\n\nclass MyLabel{\n constructor(public year: number, public isCollapsed: boolean){}\n}\n\n\nAnd then in the html you could use it like:\n\n<div *ngFor=\"let label of labels\">\n<div class=\"company\"><a (click)=\"label.isCollapsed = !label.isCollapsed labelStyle = {color: 'gray'}:labelStyle = {color: '#337ab7'}\" [ngStyle]=\"labelStyle\">{{label.year}}</a>\n </div>\n <div [ngbCollapse]=\"label.isCollapsed\">\n <div class=\"item\" *ngFor=\"let product of products\">\n <div class=\"meta\" *ngIf=\"product.year === label.year\">\n <div class=\"details\">\n <div [innerHTML]=product.reference></div>\n </div>\n </div>\n </div>\n </div>\n\n\n",
2017-05-15T19:36:23
yy