1

So I am making an application that require me to display the elements in random order, but because of the nature of the application I am not allowed to change the ngFor. So how do I make a ngFor display its content randomly?

2 Answers2

1

You can try something like this

<div *ngFor="let element of elements; let i= index">
    <div *ngIf="(i+ 1) % number == 0">
       {{ element }}
     </div>
</div>

In typescript you can add

number = Math.floor(Math.random() * 10) + 1
Bozhinovski
  • 2,496
  • 3
  • 20
  • 38
1

why don't you change indexing in ts, I mead the element on which you are applying randomization

Like

Consider elem is original Array

const newElemArr = [];

getRandomElem() => {
    const pushElem(elem[getRandomValue(0, elem.length)]);
    newElemArr.push(pushElem);
    elem.splice(elem.indexOf(pushElem, 1);
    if (elem.length === 1) {
        newElemArr.push(pushElem);
    } else {
         getRandomElem();
    }
}


getRandomValue(min, max) { // min and max included 
     return Math.floor(Math.random() * (max - min + 1) + min);
}

Here what I am doing is recursively generating random value, get value of that index from original array and push it to new array.

So new array will always have random values.

Kiran Shinde
  • 5,732
  • 4
  • 24
  • 41