Suriya Ganesh
Suriya Ganesh

Reputation: 85

I am unable to add elements to a array in angular with push method

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));  

Upvotes: 1

Views: 90

Answers (2)

Aniruddh Thakor
Aniruddh Thakor

Reputation: 1616

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

Upvotes: 1

Ricky Mo
Ricky Mo

Reputation: 7628

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>

Upvotes: 1

Related Questions