Add unique value for each element of Angular 2 HTML iteration
I have a problem with Angular 2. I want to make a List HTML like this:
<ul>
<li>
<li>..
</ul>
With links, but I don't know how to add an iteration argument to an HTML entity in NG2. This is my code:
<ul>
<li *ngFor="let item of geoNames | filterBy: userFilter"
(click)="showNameG= !showNameG" >
<a>{{ item.name }}</a>
</li>
</ul>
<div *ngIf="showNazwyG">
<show-NameG></show-NameG>
</div>
And I want to add a different name for each of the li elements to be recognized. In AngularJS it worked like this:
(click)="showNameG{{index}}= !showNameG{{index}}"
+3
source to share
3 answers
*ngFor
provides a context variable index
<li *ngFor="let item of geoNames | filterBy: userFilter; let i=index"
(click)="showNameG[i]= !showNameG[i]" ><a>{{ item.name }}</a></li>
Update
<li *ngFor="let item of geoNames | filterBy: userFilter; let i=index"
(click)="self['showNameG'] + i = !self['showNameG']" ><a>{{ item.name }}</a></li>
export class MyComponent {
get self() {
return this;
}
}
+4
source to share
You must add the following to your * ngFor:
let index = index;
In the end, you should have this:
<ul>
<li *ngFor="let item of geoNames | filterBy: userFilter; let index = index;" (click)="showNameG[index] = !showNameG[index]" ><a>{{ item.name }}</a></li>
</ul>
Here is a good description of * ngFor: https://angular.io/docs/ts/latest/api/common/index/NgFor-directive.html
0
source to share