Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create local variable in *ngFor

Tags:

angular

Is it possible to create local variable in *ngFor? For example:

<div *ngFor="let user of users; let myVariable = 0">
like image 647
Stack Over Avatar asked Jan 08 '18 07:01

Stack Over


People also ask

What is * in ngFor angular?

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

Can you have 2 ngFor?

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.

What is the syntax for ngFor directive?

It's a shortcut to the following syntax: template=“ngFor let item of items” .


2 Answers

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>
like image 176
tropicana Avatar answered Sep 30 '22 17:09

tropicana


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.

like image 22
Tim Avatar answered Sep 30 '22 19:09

Tim