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?
Asked
Active
Viewed 1,161 times
1
-
What are you allowed to change? – ConnorsFan Mar 31 '20 at 13:04
-
You mean you can not change HTML code but you can change the array that it is targeting? – palaѕн Mar 31 '20 at 13:04
-
Randomize the array before displaying it: https://stackoverflow.com/a/2450976/6513921 – ruth Mar 31 '20 at 13:06
2 Answers
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