Random product show


#1

Hi all,

When I have a sql query I can select items from a database and than random show an item. Is there a way of doing that with Ionic and a ngfor query?


#2
function getRandomInt(max) {
  return Math.floor(Math.random() * Math.floor(max));
}

See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random


#3

Thanks :slight_smile: I will try this


#4

If you are showing one random item, ngFor should not be involved. Do not do this with a function call or a pipe. Arguably the most important rule for making performant Angular applications is that all bindings should be as light as possible, and this means just a simple property access whereever you can.

So let’s say you have an array of N products called products.

If you don’t care about showing duplicates now and again, when the products array is populated, you could have a property named featuredProduct and assign products[getRandomInt(this.products.length)] using @robinyo’s function to it, and then bind to featuredProduct in your template.

If you do care about avoiding duplicates, what I would do is to shuffle the products array once and store it along with an integer ptr indicating how many have been shown. Then, on each interaction, you increment ptr and bind to products[ptr] in the template.