Unable to retrieve a random element from an array in Angular 10

I'm attempting to shuffle items (cards that have English words) from a flashCards array, so that each card can appear randomly when the user reloads the page. I tried using the Math.floor(Math.random()) function, but it's not working. How can I randomly display cards from an array of cards?

home.page.html:

<ion-content padding>
     <app-flash-card *ngFor="let card of flashCards" [ngClass]="randomize()">
        <div class="flash-card-front">{{card.front}}</div>

        <div class="flash-card-back">{{card.back}}</div>
     </app-flash-card>  
</ion-content>

home.page.ts:

export class HomePage {

    flashCards: any;
  
  constructor(public navCtrl: NavController) {
        this.flashCards = [
            {back: 'accreditation', front: 'official approval'},
            {back: 'AIDA', front: 'Attention, Interest, Desire, Action (Model for advertising effectiveness)'},
            {back: 'airtime', front: 'broadcasting time'},
            {back: 'ambient noise', front: 'background noise'},
            {back: 'ambitious', front: 'ambitious, driven'}
        ];
    };
    randomize(){    
        var index=Math.floor(Math.random()*this.flashCards.length);
        return this.flashCards[index];
    }
}

Answer №1

Here's a comprehensive solution: Following the suggestions from the comments, you can utilize the existing shuffle function by accessing it either in the constructor or the ngOnInit function (following Angular conventions). I stored your flashCards in a new var and assigned it to this.flashCards after shuffling (which is later referenced in your HTML). This ensures that the array is shuffled before being displayed:

import { OnInit } from '@angular/core';

export class HomePage implements OnInit {

    flashCards: any;
  
    constructor(public navCtrl: NavController) { }

    ngOnInit(): void {
        var flashCards = [
            {back: 'accreditation', front: 'offizielle Zustimmung'},
            {back: 'AIDA', front: 'Attention, Interest, Desire, Action (Aufmerksamkeit, Interresse, Wunsch, Handlung)-> Modell zur Werbewirkung'},
            {back: 'airtime', front: 'Sendezeit'},
            {back: 'ambient noise', front: 'Umgebungsgeräusch'},
            {back: 'ambitious', front: 'ehrgeizig,strebsam'}
        ];
        this.flashCards = this.shuffle(flashCards)
    }

    shuffle (array) {
        var currentIndex = array.length, temporaryValue, randomIndex;

        // While there remain elements to shuffle...
        while (0 !== currentIndex) {

            // Pick a remaining element...
            randomIndex = Math.floor(Math.random() * currentIndex);
            currentIndex -= 1;

            // And swap it with the current element.
            temporaryValue = array[currentIndex];
            array[currentIndex] = array[randomIndex];
            array[randomIndex] = temporaryValue;
        }

        return array;
    }
}

Furthermore, you can remove the [ngClass] and simply structure it like this:

<ion-content padding>
     <app-flash-card *ngFor="let card of flashCards">
        <div class="flash-card-front">{{card.front}}</div>

        <div class="flash-card-back">{{card.back}}</div>
     </app-flash-card>  
</ion-content>

The shuffling is handled in ngOnInit and using [ngClass] would not be the appropriate approach.

Best of luck!

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

Can you provide guidance on how to access my account using the code that I have?

I'm having trouble getting the login functionality to work properly with this code. When I click the login button, nothing happens - no errors are displayed either. Can you help me identify what might be causing this issue? login() { var url = &ap ...

Exploring the options variables within CLI commander Js action

As a newcomer to developing CLI apps, I've chosen to work with ts-node and commander. However, I'm currently facing a challenge in understanding how to access the options that users pass into my command action. program .version(version) .nam ...

What could be causing the error related to "Implicit any return type" in this situation?

I expect the code below to pass the type check successfully: class MyClass<T extends object, P extends string = string> { method(thing: Thing) { return thing.method(this); } } declare class Thing { method(entity: MyClass<any&g ...

Issue with Angular Route Guard - Incorrect redirection to login page

I'm encountering an issue with my Angular app where even after the JWT token has expired, I am still able to navigate within the application without any API data being accessible. I've double-checked my setup and it seems right, but for some reas ...

How can I effectively monitor a group of ongoing observables in RxJS that have not yet finished?

I have a series of TypeScript observables (Observable<boolean>) that emit multiple times and then complete. I need to remove these observables from a collection once they complete, but while they are still active, I require access to their latest val ...

I am searching for the vector geometric shapes svg elements that are commonly utilized in design editors. Can you point

When it comes to design editors, there are plenty of options such as Canva, Vistacreate, and Adobe Express. Each one uses a variety of styles for elements/objects/shapes. Are there any databases where I can find these resources? Some popular places include ...

Angular: NaNa: Attempting to access a property of an undefined variable

I've encountered these errors although the values are displayed correctly in the browser. I'm unsure about how to resolve this issue. ERROR TypeError: Cannot read property 'length' of undefined ERROR TypeError: Cannot read property &ap ...

What is the importance of maintaining immutability for objects in Redux?

What is the importance of immutability in Redux? While I understand that frameworks like Angular2 use onPush to leverage immutability for quicker rendering of views, I'm interested in learning about other reasons why Redux emphasizes immutability desp ...

Avoid employing the CanDeactivate guard in conjunction with the submit button

I have implemented a canDeactivate guard that is working correctly. However, I want to prevent the guard from being called when the submit button is used, and only activate it when navigating through other means. Is there a way to achieve this? import { ...

Show a stylish container when the server encounters an HTTP error with status code 500

My approach for error handling involves a straightforward ErrorHandler class structured like this: export class AppErrorHandler implements ErrorHandler { handleError(error : any){ //console.log('test error ', error.status); ...

Retrieve a HashMap through an HTTP GET request using Angular 10

I am currently using the following versions: Angular CLI: 10.0.1 Node: 12.18.2 OS: win32 x64 Angular: 10.0.2 In my setup, I have a Java Spring Boot service that is functioning correctly and returns data as a HashMap. Map<String, List<String>&g ...

Angular 8 bug: Requiring 2-3 arguments, received only 1

Currently deepening my knowledge in Angular and I encountered a situation within one of my services agree(id: string) { const headers = new HttpHeaders('Content-Type: application/json'); return this.HttpClient.put(`${this.apiUrl}/agree/` ...

What causes the generation of an outdated object when utilizing the let and new keywords to create a new object within a service function?

Hey there, looking for a basic auth authentication service in angular2? Here's the issue I'm facing: When a user logs in for the first time, everything works smoothly. However, if they try to log in with a different account for the second time, ...

Error encountered during Cordova installation: potential path problem - error code ENOENT

After successfully installing Xcode and NodeJS, I encountered an error while trying to install Cordova. The error message indicated that a file was missing (possibly due to an incorrect path). Luciens-MacBook-Pro:~ lucientavano$ npm cache clean Luciens-Ma ...

When I click on the button, the output does not appear

Even though I know how to write this in pure javascript, I am new to angular so when I click submit, nothing happens and I don't get any result. index.html <input type="text" ng-model="username" placeholder="Username"> <input type=" ...

Define class attributes within a TypeScript callback function

I have encountered an issue with my method involving a subscription to an event from a pub sub messaging service. The problem arises when I attempt to define a class property within the callback function, only to find that the property returns as undefin ...

retrieve object from s3 using angular and open it as a pdf

I'm attempting to access a file from an s3 bucket using Angular and display it as a PDF. I have a node service set up to retrieve the object, which I then call from Angular. However, when I try to open the PDF in Angular, it appears as a blank (white) ...

The use of await can only occur inside an async function

Can someone explain the proper placement of the async keyword for me? I've tried a few different spots, but keep encountering the same error. async addNewCategory() { let alert = this.alertCtrl.create({ title: 'New Category', ...

Confirm whether the Iterator type is the same as the AsyncIterator type

Is there a clever JavaScript technique to differentiate between Iterator and AsyncIterator without initiating the iteration process? I'm attempting to create a type checker like this: function isAsyncIterator<T>(i: Iterator<T> | AsyncIter ...

problem with adjusting the form field depending on the circumstances

I am facing an issue with a form that displays a dropdown containing values such as users, receipts, companies, and reviewer. The visibility of these values should be based on the user's role. For example, if the role is admin, only users, receipts, a ...