0

I have this array with static image

  public ImageList: Array<any> = [
    {"id" : 1, "Url" :"assets/images/...svg"}, 
    {"id" : 2, "Url" :"assets/images/...svg"}, 
    {"id" : 3, "Url" :"assets/images/..."}, 
    {"id" : 4, "Url" :"assets/images/..."}
  ];

i have this another data array

data:any=[];

 <div *ngFor="let row of data; let i=index">

   <img src=''/>

</div>

now inside this for loop i want to pick random image from the for loop and display in the image tag.

Any solution to generate random number from 1 to 4 inside for loop.

Thanks

user3653474
  • 3,393
  • 6
  • 49
  • 135
  • 1
    Does this answer your question? [Generate random number between two numbers in JavaScript](https://stackoverflow.com/questions/4959975/generate-random-number-between-two-numbers-in-javascript) – Naren Murali Dec 08 '22 at 10:49
  • @NarenMurali I want it in angular, inside loop how will i access random numbers – user3653474 Dec 08 '22 at 10:51
  • you can run a `foreach` or `map` operation for data array and then set the random index value inside the elements of data array! – Naren Murali Dec 08 '22 at 10:52

1 Answers1

0

I personally think that usecase is a great example to create a structural directive you can reuse!

import { Directive, Input, TemplateRef, ViewContainerRef } from '@angular/core';

interface RandomContext<T> {
  appRandom: T[];
  $implicit?: T;
  controller: {
    next: () => void;
  };
}

@Directive({
  standalone: true,
  selector: '[appRandom]',
})
export class RandomDirective<T> {
  private context: RandomContext<T> = {
    appRandom: [],
    $implicit: undefined,
    controller: {
      next: () => this.pickNewElement(),
    },
  };

  @Input()
  set appRandom(elements: T[]) {
    this.context.appRandom = elements;
    this.pickNewElement();
  }

  constructor(
    private templateRef: TemplateRef<any>,
    private viewContainer: ViewContainerRef
  ) {
    this.viewContainer.createEmbeddedView(this.templateRef, this.context);
  }

  private pickNewElement(): void {
    this.context.$implicit =
      this.context.appRandom[
        Math.floor(Math.random() * this.context.appRandom.length)
      ];
  }
}

Example usage:

<ng-container
  *appRandom="
    ['foo', 'bar', 'hello', 'world'];
    let random;
    let ctrl = controller
  "
>
  <div>{{ random }}</div>
  <button (click)="ctrl.next()">Randomize</button>
</ng-container>

Try this out: https://stackblitz.com/edit/angular-ivy-bvsfbe?file=src/app/app.component.html

Of course you can leave out the button, I added it for demonstration purposes. Instead of the string you add your object array, random yields the random picked object then, you can also pick another name instead of random. This would look like:

<div *appRandom="ImageList; let image">
  <img [src]="image.Url"/>
</div>

Clean template, isn't it?

MoxxiManagarm
  • 8,735
  • 3
  • 14
  • 43