CodeMonkey
CodeMonkey

Reputation: 12424

Run ngFor several times

I'm using Angular 7.

I got a an array and I'm doing the usual ngFor in the HTML:

<mat-card *ngFor="let card of cardNames">

Is there a way to iterate over the cardNames elements more than once?

Upvotes: 0

Views: 957

Answers (1)

dev-dan
dev-dan

Reputation: 6283

"if the array was with "a", "b", "c", i want it to either iterate like this: abcabc or like this: aabbcc"

Heres a weird one for you with the *ngFor, use repeat and split to determine how many time you want the array to repeat and then within that show the array you would like. Weird but gives what you want.

public fetchData = ['a', 'b', 'c'];

Then in the template. The 2 is the count for how many time's you want to repeat the nested *ngFor.

<div *ngFor = "let x of ' '.repeat(2).split('')">
  <div *ngFor="let titlee of fetchData">
      {{ titlee }}
  </div>
</div>

This gives printed in DOM.

a
b
c
a
b
c

Im not 100% sure as to if this has any associated problems with it, just one way of getting to the answer you are looking for.

Repeat HTML element multiple times using ngFor based on a number.

For the second way, just be lazy I guess. Instead of iterating of the array with the values you want iterating one. Make a new array, for each index of the old array push it to the new one twice. Then iterate over it as usual with a standard *ngFor

  public fetchData = ['a', 'b', 'c'];
  public dupedData = [];

  public ngOnInit(): void 
  {
    this.fetchData.forEach(data => 
    {
      this.dupedData.push(data);
      this.dupedData.push(data);

    });
  }

Then simple template.

<div *ngFor="let titlee of dupedData">
  {{ titlee }}
</div>

Which will give you

a
a
b
b
c
c

The following would give the same effectively.

<div *ngFor="let titlee of fetchData">
  <div>{{ titlee }}</div>
  <div>{{ titlee }}</div>
</div>

Upvotes: 3

Related Questions