Reputation: 287
Is it possible to create local variable in *ngFor? For example:
<div *ngFor="let user of users; let myVariable = 0">
Upvotes: 11
Views: 13382
Reputation: 5839
It's not possible to create a custom local variable within an *ngFor
, you can only use the 8 built-in ones.
You can work around this limitation by creating an array in the component class and referencing it within the template. You didn't specify your use case, so let's imagine that what you want is a counter which increments when the user clicks the div
.
In your component, you create your counter
array with its initial values:
counter = this.users.map(u => 0);
You can reference this within your template, using the index of the *ngFor
to identify the correct element of the array.
<div *ngFor="let user of users; let i = index" (click)="counter[i] = counter[i] + 1">
User clicked {{counter[i]}} times.
</div>
Upvotes: 5
Reputation: 1433
You can use ng-container with a ngIf to achieve this.
<div class="message-list">
<ng-container *ngFor="let message of messages">
<ng-container
*ngIf="{
isCurrentUser: message.createdBy.email === currentUser.email
} as locals"
>
<div
class="message"
[ngClass]="{ 'message--right-aligned': locals.isCurrentUser }"
>
<div>{{ message.text }}</div>
<div [ngClass]="{ bold: !locals.isCurrentUser }">
{{ message.createdBy.name }}
</div>
</div>
</ng-container>
</ng-container>
</div>
Upvotes: 14
Reputation: 2192
You can't create local variables. Sometimes you can get the index of the item in the array we are iterating over. You can do this by adding another variable to our ngFor expression and making it equal to index, like so:
<ul>
<li *ngFor="let user of users; let i = index">
{{ i + 1 }} - {{ user.name }}
</li>
</ul>
If you need a variable in your component, you need to create it in component class before use it. For example:
@Component({
selector: 'ngfor-example',
template: `<h4>NgFor</h4>
<ul>
<li *ngFor="let user of users">
{{ variable }} - {{ person.name }}
</li>
</ul>`
})
class NgForExampleComponent {
variable = 0;
}
Upvotes: 2