Is it possible to create local variable in *ngFor? For example:
<div *ngFor="let user of users; let myVariable = 0">
*ngFor is a predefined directive in Angular. It accepts an array to iterate data over atemplate to replicate the template with different data. It's the same as the forEach() method in JavaScript, which also iterates over an array.
So you cannot use two ngFor s on the same element, but you can use the index, if both arrays are of the same size, to check whether or not there is a value.
It's a shortcut to the following syntax: template=“ngFor let item of items” .
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>
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>
Working demo on stackblitz.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With