Home > front end >  I am unable to add elements to a array in angular with push method
I am unable to add elements to a array in angular with push method

Time:12-29

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

CodePudding user response:

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  (click)="nextSequence()">click here</button>

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

CodePudding user response:

Use *ngFor to iterate and display an array.

<h1>{{randomChosenColour}}</h1>
<h1 *ngFor="let colour of gamePattern">{{colour}}</h1>
<button  (click)="nextSequence()">click here</button>
  • Related