Nitneq
Nitneq

Reputation: 711

How to make an infinite loop on array with ngFor

I'm coding a simple angular 4 game, a quiz where players have to answer one by one. I have a simple array like this :

this.listPLayers = [{name:'Toto', score:0}, {name:'Tutu',score:0},{name:"Titi',score:O}];

When player answer, I handle this function :

 getAnswer(answer, player){
      this.nbOfQuestions = this.nbOfQuestions - 1;
      this.listPlayers.splice(0,1);

        if(answer.isTrue == true) {
            player.score = player.score + 1;
            this.showModal(right);
        } else {
            this.showModal(bad);
        }
}

And HTML :

<span class="player" *ngFor="let player of listPlayers.slice(0, 1)">{{player.name}} : </span>

The goal is to make an infinite loop on listPlayers, but without lose the score.

EDIT : On HTMl I just take the first index of the array to display it. Every time a player answer to a question, I splice the array to display the next player. To make it simple the ngFor should display (one bye one):

Toto, Tutu, Titi, Toto, Tutu, Titi, Toto, Tutu, Titi, ....

Upvotes: 0

Views: 313

Answers (1)

Randy Casburn
Randy Casburn

Reputation: 14165

We don't code long running processes in the browser the way we do with platform code. So your thought of an infinite loop makes sense in the context of a server process for instance.

On the client we use the eventing system to accomplish the same goal.

  1. Set up an action to occur upon some stimulus
    • run getAnswer when question answered
  2. Set stimulus (question answered) to notify of stimulus
    • emit event notifying that question has been answered

AngularJS provides $broadcast and $emit and Angular provides the EventEmitter Class for these purposes.

The docs for EventEmitter have a good example of how to accomplish this with Angular.

Upvotes: 0

Related Questions