What is the best way to load information from the initial array onto a randomly chosen card?

Is there a way to populate data from the first array on a randomly selected card?

I am trying to create a random card in Angular, where when I click on the first card, it will display the first value from the array and automatically fill the other cards with the remaining values. Once clicked, the action can only be done once. Thank you for your help.

Here is the code I have: sandbox

Here is my angular component:

export class AppComponent {
arrayData: any = \["one", "two", "three"\];
value: any = "";

clicker() {
this.value = this.arrayData\[0\];
}
}

And here is the HTML:

<div class="card" \*ngFor="let v of arrayData" (click)="clicker()"\>
<label\>{{value}}\</label\>
<p>
  How can we show arrayData[0] on the selected card and display arrayData[1] and arrayData[2] on the other cards before disabling further clicks?
</p>

I would greatly appreciate any assistance in solving this issue! Thank you.

Answer №1

When looping through an array in HTML, ensure that you are displaying different values from the elements rather than repeating the same value multiple times using this.value. To achieve this, loop through the array and display its elements only after a card has been clicked. You can use the json pipe if the elements are objects.

<div class="card" *ngFor="let v of arrayData" (click)="clicker()">
  <label *ngIf="clicked">{{v | json}}</label>
</div>
<p>
  How to display arrayData[0] on card selection, fill other cards with arrayData[1] and arrayData[2], then disable further clicks.
</p>

and in TS:

clicked = false;

clicker() {
  this.clicked = true;
}

Answer №2

Displaying cards according to the array length - check. Each card reveals the value of the variable value, which remains constant.

<div class="card" *ngFor="let v of arrayData" (click)="clicker()">
<label>{{value}}</label>
</div>

The cards are not linked to any specific values as they stand.

To improve this, consider adding: (Alternatively, dynamically generate array objects based on arrayData length)

  cards: any = [
    { id: 1, value: null },
    { id: 2, value: null },
    { id: 3, value: null }
  ];

Now you can assign a value to each card. You can then display them in the template:

<div
  class="card"
  *ngFor="let card of cards; let i = index"
  (click)="onCardClick(i)"
>
  <label>{{ card.value }}</label>
</div>

{{ card.value }} represents the unique value for each card.

Note the usage of *ngFor="let card of cards; let i = index", marking an incremental index that identifies the clicked card.

In the onCardClick method, we verify if the user has already interacted with that particular card.

  onCardClick(index: number) {
    if (!this.shuffled) {
      this.clicker(index);
    }
  }

Alternatively, you can provide feedback to the user through an alert or similar mechanism indicating prior interaction.

If valid, proceed with calling the clicker method.

  clicker(index: number) {
    let arrayDataIndex = 1;

    this.cards.forEach((card: any, idx: number) => {
      if (index === idx) {
        card.value = this.arrayData[0];
      } else {
        card.value = this.arrayData[arrayDataIndex];
        arrayDataIndex++;
      }
    });

    this.shuffled = true;
  }

Within the foreach loop, iterate over the remaining elements of cards. If the element matches the clicked card's index, assign the initial arrayData value. Otherwise, assign subsequent values from arrayData.

Finally, set this.shuffled = true to prevent repeated actions.

I hope I have captured the essence of your requirements :)

Visit the functional example at https://codesandbox.io/s/loving-wind-gku7vl

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

Verifying User Permissions with Angular 2/4 and API

I am currently in the process of developing an Angular 2/4 application that interacts with an API built in Laravel 5.4. One area I'm seeking guidance on involves checking authentication and permissions on the backend through Angular. I want to verify ...

An easy method to define argument types for every function type in TypeScript

How can I assign argument types to each function type in TypeScript? Each function has a parameter associated with it. [Example] type F1 = (arg: number) => void; type F2 = (arg: string) => void; const caller = (f: F1 | F2) => (n: number | strin ...

Showcasing only one item at a time in AngularJS 1.x with ng-repeat; by clicking on "next", the subsequent item will be displayed,

Currently, I am working on a quiz web application that requires displaying a total of 100 questions across 3 different tabs - Math, GK, and English. The questions are filtered using an Angular filter. However, I'm facing an issue where each tab is sho ...

Responding with a 404 Error in Node.js and Express with Callbacks

Apologies for the lackluster title, I couldn't come up with anything better. Let's delve into the following code snippet: app.use(function(request, response){ request.addListener('end', function() { parseUrl(request.url, fu ...

Is it achievable to send information back to a Servlet from JavaScript?

I am currently working on setting up a Servlet that utilizes JDBC for database interactions. My goal is to allow users to log in through a login form and then view the list of available databases in MySQL. I am implementing this functionality dynamically ...

What is the method for extending props from React.HTMLProps<HTMLButtonElement>?

"react": "^17.0.2", "typescript": "^4.2.4" Can someone help me understand how to extend props from React.HTMLProps? import { FC, HTMLProps } from 'react' export interface SliderButtonProps extends HTMLPro ...

Add a hash to the file name of the JSON translation asset

To prevent caching issues, I choose to store my translation files as JSON in /src/assets/i18n. To achieve this in Angular, I am looking for a way to add a unique fingerprint or hash to the filename of the file and use that hashed name when retrieving the ...

A guide on navigating through an array nested within an object

I have been diving into the world of ReactJS, experimenting with different APIs to fetch and manipulate data. Currently, I am working with the Flickr API which returns data structured as "An array inside an object". { "photos": { "page": 1, "page ...

"Exploring the Wonders of Regular Expressions in JavaScript: Embracing the Truth and All

Hey there! I've been working on a JavaScript script to test password field validation. As of now, I have successfully made the script display an alert when the requirements are not met. However, I am now facing an issue regarding what action to take o ...

Utilize Material UI's Datagrid or XGrid components to customize the rendering

There is a section from Material UI discussing renderHeader in the DataGrid and Xgrid components. https://material-ui.com/components/data-grid/columns/#render-header The documentation describes how to add additional content to the header, but what if I w ...

The TypeScript error "Issue with Type Assertion: 'This expression is not callable Type'...' has no call signatures" occurs when there is a missing semicolon

Here's a simplified version of our original code: const start: number = 10 const end: number = 20 (someElement as HTMLInputElement).setSelectionRange(start, end) We encountered an error with the 20, where a red squiggly line appeared indicating ...

Increase the size of the textarea when it is clicked on and revert back to its original size when it

My question revolves around a text area that I am trying to manipulate through jQuery. The desired functionality is to increase the height of the text area whenever someone clicks on it, and decrease the height when clicking anywhere else on the screen. & ...

When restarting nginx, Angular fails to display the index page

On my VPS server, I have an application with the backend coded in node.js and the frontend in Angular. After restarting nginx, I encountered some issues where my API stopped working on HTTPS and only functioned on HTTP (previously, I was able to make requ ...

sending an array from one CodeIgniter view to another view via Ajax

In the following code segments of my application, myArray is an array where each element contains a few objects that I need to use in a second view. When I use alert(myJSON);, I am able to see the array in the alert window. However, when the view loads, i ...

Showcasing the Monday date exclusively on the x-axis of the line chart using ng2-charts

Currently, I am utilizing ng2-charts within my angular 6 application. The line chart I have implemented shows values on the y-axis and dates on the x-axis. To visualize this, you can view the line chart image. My specific requirement is to only display ...

What are the steps to create a dynamic navigation menu in Angular 2?

I have successfully implemented this design using vanilla CSS and JS, but I am encountering challenges when trying to replicate it in Angular 2. Setting aside routing concerns, here is the current state of my component: navbar.component.ts import { Comp ...

What is the best way to push an object directly outward in the camera's view in Three.js?

My understanding is that finding a direction vector and multiplying it by the coordinates is necessary for this task, but I am unsure how to proceed with this method. Unfortunately, I have not been able to locate the information needed to find a solution ...

Is there a way for me to set distinct values for the input box using my color picker?

I have two different input boxes with unique ids and two different color picker palettes. My goal is to allow the user to select a color from each palette and have that color display in the corresponding input box. Currently, this functionality is partiall ...

Is it possible to dynamically change HTML content by utilizing a JSON file?

Looking to implement a JavaScript loop (using jQuery) that can dynamically populate the HTML file with content from a JSON file based on matching <div> ids to the JSON "id" values. The solution should be scalable and able to handle any number of < ...

utilizing the default placeholder image for videos and audios within the tags

In my web application, users can share music and videos that will be stored on a server used by the application. Some audio/video files come with posters or thumbnails attached to them. I want to display these posters along with the audio or video using HT ...