1

Here I am trying to get a random number between 0 and 3 and choose an element from array buttonColours based on it and then add the same element to the array gamePattern, the randomChosencolour string(one random colour) is generated and is displayed everytime I click the button, but the gamePattern array does not seem to work,

Template HTML:

<h1>{{randomChosenColour}}</h1>
<h1>{{gamePattern}}</h1>
<button class="btn-primary" (click)="nextSequence()">click here</button>

----------
TS file:

  max_limit=3;
  min_limit=0;
  randomNumber=0;
  buttonColours = ["red", "blue", "green", "yellow"];
  randomChosenColour="";
  gamePattern =[] as any;
  nextSequence()
  { 
    this.randomNumber = this.min_limit + Math.floor(Math.random()*(this.max_limit-this.min_limit+1));
    this.randomChosenColour = this.buttonColours[this.randomNumber];
    this.gamePattern.push(this.randomChosenColour);  
    }

I tried this approach which also does not help.

this.gamePattern.push(Object.assign({}, this.randomChosenColour));  

2 Answers 2

1

Please add *ngFor to display all the colors in the array.

<h1>Random Color:{{ randomChosenColour }}</h1>
<h1 *ngFor="let color of gamePattern">{{ color }}</h1>
<button class="btn-primary" (click)="nextSequence()">click here</button>

Here is the working demo link: https://stackblitz.com/edit/angular-ivy-eagqga?file=src/app/app.component.html

Sign up to request clarification or add additional context in comments.

Comments

1

Use *ngFor to iterate and display an array.

<h1>{{randomChosenColour}}</h1>
<h1 *ngFor="let colour of gamePattern">{{colour}}</h1>
<button class="btn-primary" (click)="nextSequence()">click here</button>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.