dcp3450
dcp3450

Reputation: 11187

Angular: getting independent data for each item in ngFor loop

I'm new to Angular2+ and testing out some UI. To do so I want to place a random number inside a set of containers that are added via an ngFor:

<div class="table-row" *ngFor="let row of [0,1,2,3,4,5,6]">
  <div class="table-cell">{{fakeData()}}</div>
  <div class="table-cell">{{fakeData()}}</div>
  <div class="table-cell">{{fakeData()}}</div>
  <div class="table-cell">{{fakeData()}}</div>
</div>

This basically produces 6 rows with 4 columns that should hold a temp number.

When I used fakeData = Math.floor(Math.random() * Math.floor(300)); it produced the same number for each cell. When I made this a function (like above) the numbers are different in each cell but they keep changing. Obviously getting data on a per row/cell will come in handy when I start pulling and placing real data in here.

Upvotes: 1

Views: 1193

Answers (4)

Patricio Vargas
Patricio Vargas

Reputation: 5522

I got it to work the following way:

In your html:

   <div class="table-row" *ngFor="let row of [0,1,2,3,4,5,6]">
        <div class="table-cell">{{fakeData()}}</div>
      </div>

In your .ts file:

 fakeData() {
    return  Math.floor(Math.random() * Math.floor(300));
  }

Upvotes: 0

HMarteau
HMarteau

Reputation: 654

When you call a function directly from the template, it is called each frame. So your function fakeData() is doing its job by giving you new random numbers every frame

I don't know why you want a random number for each cell but one thing usefull is the index of *ngFor

<div class="table-row" *ngFor="let row of [0,1,2,3,4,5,6]; index as i">
  <div class="table-cell">{{100*i + 1}}</div>
  <div class="table-cell">{{100*i + 2}}</div>
  <div class="table-cell">{{100*i + 3}}</div>
  <div class="table-cell">{{100*i + 4}}</div>
</div>

That will give you something like this (below). Because i (index) is the index of the loop you are currently running

1 2 3 4 101 102 103 104 201 202 203 204 , etc

Upvotes: 1

user4799206
user4799206

Reputation:

Reason is that angular continously updates the page when it recogniozes change.

To solve your issue you can fill your data to an array(maybe into two-dimentional array which depends on your need) in ts, then call ngFor in html.

Upvotes: 0

Why not use an array of objects ? Your data will probably end up being one.

myData = [
          {key1: 'val1', key2: 'val2', key3: 'val3', key4: 'val4'},
          {key1: 'val1', key2: 'val2', key3: 'val3', key4: 'val4'}
         ];

<div class="table-row" *ngFor="let obj of myData">
  <div class="table-cell">{{obj.key1}}</div>
  <div class="table-cell">{{obj.key2}}</div>
  <div class="table-cell">{{obj.key3}}</div>
  <div class="table-cell">{{obj.key4}}</div>
</div>

Upvotes: 0

Related Questions