Incorporate a random number generation within a specified index range while looping in Angular

I am working with an array that contains static images:

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/..."}
  ];

Additionally, I have another array called data.

data:any=[];

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

   <img src=''/>

</div>

While iterating through this data in a loop, I need to randomly select an image from the ImageList and display it on the image tag.

Is there a solution to generate a random number between 1 and 4 within the for loop?

Thank you

Answer №1

In my opinion, the usecase provided is an excellent example of how to create a reusable structural directive!

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

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

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

  @Input()
  set appCustom(items: T[]) {
    this.context.appCustom = items;
    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.appCustom[
        Math.floor(Math.random() * this.context.appCustom.length)
      ];
  }
}

Usage example:

<ng-container
  *appCustom="
    ['apple', 'banana', 'orange', 'pear'];
    let fruit;
    let ctrl = controller
  "
>
  <div>{{ fruit }}</div>
  <button (click)="ctrl.next()">Next Fruit</button>
</ng-container>

Give it a try: https://stackblitz.com/edit/angular-ivy-bvsfbe?file=src/app/app.component.html

You can customize the name of the variable that holds the random item. For instance:

<div *appCustom="CarList; let car">
  <p>{{ car.Name }}</p>
</div>

Simple and clean template, right?

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Having trouble getting React app to recognize Sass properly

I have been working on developing a React app using TypeScript and the SASS preprocessor. Here is an example of my code: // Button.tsx import React from 'react'; import './Button.scss'; export default class Button extends React.Compone ...

How can I verify if there are duplicate items in the cart using Angular 5?

As a newcomer to Angular 5, I am delving into creating a basic shopping cart to master the framework. However, I am currently facing a dilemma regarding how to handle duplicate entries in the cart data. Specifically, I am unsure whether I should store obje ...

Can you specify the necessary import statement for CallableContext?

My Google Cloud function is simple and looks like this: import * as functions from 'firebase-functions'; var util = require('util') export const repeat = functions.https.onCall( function (data, context) { console.log(&apo ...

What steps do I need to take to integrate the Firebase Admin SDK into my Angular project?

Is there a way to integrate Firebase Admin SDK into my Angular application? Currently, I am using Firebase Authentication services in my application and everything I need for user registration and authentication is handled by Angularfire2. I've read ...

Issue encountered: TypeScript compiler (tsc) failed to compile a dependent library within a project, specifically one that depends on a JavaScript library and @types typing package

Imagine a scenario where a library, let's name it LibraryA, relies on another library called js-yaml without type definitions. To make this work, LibraryA has a devDependency called @types/js-yam in its package.json. LibraryA itself compiles smoothly. ...

Exciting ngClass variation

I am facing a challenge of adding multiple classes to an element, with one of them being conditional. After referencing the documentation, I came across this method: <some-element [ngClass]="{'first': true, 'second': true, 'thi ...

Is "await" considered as a reserved word in ReactJS when using TypeScript?

I am trying to implement async await in my code, but I keep getting an error that says await is a reserved word. Here is the snippet of my code: public componentDidMount() { this.startDrag(); } private startDrag = async () => { const eleme ...

Utilize toggle functionality for page rotation with rxjs in Angular framework

Managing a project that involves a container holding multiple cards across different pages can be overwhelming. To address this, the screen automatically rotates to the next page after a set time interval or when the user presses the space bar. To enhance ...

Step-by-step guide on invoking a WPF c# method from a .ts file with the assistance of dotnetbrowser

Referring to the Account class, I am trying to figure out how to call a C# method from Angular's .ts file in Angular, while also passing data to the method. mainLayout.Children.Add((UIElement)webView.GetComponent()); webView.B ...

Encountering a Pulumi problem during infrastructure packaging: Unable to utilize an import statement beyond a module

I am experimenting with a new approach in Pulumi: bundling the infrastructure. My approach involves deploying a simple S3 bucket by leveraging an npm package. Here is the content of my bucket npm package: index.ts import * as aws from "@pulumi/aws&q ...

Implementing the withAuthenitcationProps method in all page.tsx files to integrate Amazon Cognito authentication

I have been working on my Next.js app and wanted to share the project structure with you: ├── README.md ├── amplify │ ├── #current-cloud-backend │ ├── README.md │ ├── auth │ ├── backend │ ├── cl ...

Error in NextJS: The name 'NextApplicationPage' cannot be found

const { Component, pageProps}: { Component: NextApplicationPage; pageProps: any } = props After implementing the code above with 'Component' type set to NextApplicationPage, an error message pops up stating, The name 'NextApplicationPage&ap ...

The Vue $refs Object is classified as 'unidentified' in nature

I'm encountering an issue while attempting to utilize $refs in my Vue 3 application. Each time I try, I receive the Typescript error stating that "Object is of type 'unknown'". I am uncertain about how to resolve this problem. Here's ...

The module declaration is triggering a lint error that reads "Unexpected token, expecting '{'"

To address the absence of available types for a library, I created the file omnivore.d.ts in TypeScript. Within this file, I added the following line: declare module '@mapbox/leaflet-omnivore' Upon running vue-cli-service lint in my project, an ...

Determine the generic type of the parent class based on the constructor of the child class

Below is a code snippet illustrating the issue at hand: class Parent<T = unknown> { constructor(private prop: T) {} getProp(): T { return this.prop; } } class Child extends Parent { constructor() { super({ ...

Navigating with AngularJS 2 on Internet Information Services (IIS)

I'm facing an issue with my ASP.NET CORE application that uses angular2 routing. While running the app locally, the routes resolve correctly. However, when I deploy it to a server (running on IIS 7), the routes seem to be appending the folder director ...

Steps to implement Angular routerLink on an image for seamless navigation to a different component

Is there a way to create an interactive image that leads to other sections within Angular? The intention is for this particular image to serve as a miniature profile picture of the existing user, located in the navigation bar. <img ngSrc="{{User.photo ...

Angular EventEmitter coupled with Callbacks

In order to create a custom button component for my angular application and implement a method for click functionality, I have the following code snippet: export class MyButtonComponent { @Input() active: boolean = false; @Output() btnClick: EventEmit ...

Issues arising when routing ffmpeg to flac encoder

I am facing an issue with encoding a flac file with seektables. The ffmpeg's flac encoder does not include seektables, so I have to resort to using the flac Command Line Interface (CLI). My goal is to convert any arbitrary audio file into a seekable f ...

Accessing the Parent Variable from a Function in JavaScript: A Guide

How can you properly retrieve the value of x? let x = 5 const f = (n:number) => { let x = "Welcome"; return x * n // Referring to the first x, not the second one } Also, what is the accurate technical term for this action? ...