Reputation: 339
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>
When I do click on a label, isCollapsed change from false to true, but isCollpsed change for all iterations. Could you give me an advice for doing click and collapsing only one label?
Thanks
Upvotes: 0
Views: 777
Reputation: 1559
add isCollapsed as a property of class used by labels.
In your component, if your 'labels' is a number array, i.e. if it is currently:
labels: number[]
then change it to
labels: MyLabel[]
and after your component class add a model called MyLabel
like:
class MyLabel{
constructor(public year: number, public isCollapsed: boolean){}
}
And then in the html you could use it like:
<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>
Upvotes: 2
Reputation: 3615
You can define one field in component with index
name and set it to null
and using $index
like this:
<div class="company"><a (click)="toggleCollapsed($index) ? labelStyle = {color: 'gray'}:labelStyle = {color: '#337ab7'}" [ngStyle]="labelStyle">{{label.year}}</a>
And define toggleCollapsed(index) as follow:
toggleCollapsed(index : number){
this.index != index ? this.index = index : this.index = null;
return this.index == index;
}
Upvotes: 0