Home > Mobile >  Display random images with angular
Display random images with angular

Time:10-13

Please I asked a question about displaying random images and look at my code and still I cannot get the images display randomly when I clicked the button:

import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core';

@Component({
  selector: 'app-button',
  templateUrl: './button.component.html',
  styleUrls: ['./button.component.css']
})
export class ButtonComponent implements OnInit {
  constructor() { }
  ngOnInit(): void {
  }

  // public imageList = Array<any>;
  public imageList: Array<any> = [
    {"id" : 1, "Url" :"../assets/images/1.png"}, 
    {"id" : 2, "Url" :"../assets/images/2.png"}, 
    {"id" : 3, "Url" :"../assets/images/3.png"}, 
    {"id" : 4, "Url" :"../assets/images/4.png"},
    {"id" : 5, "Url" :"../assets/images/5.png"},
    {"id" : 6, "Url" :"../assets/images/6.png"} 
  ];

  newGame(imageList:any) {
    //console.log("new game");
    imageList[Math.floor((Math.random()*imageList.length))]; 
    //imageList = "../assets/images/"   id   png;
  }

}
HTLM <div class="btn">
    <button (click)="newGame()" class="btnNew">New Game</button>
</div>

This is the error message im getting after I did made the changes you suggested Screen shot of the code

Second screen shot

CodePudding user response:

Just have a member that you can change with your function, and use that member in your template:

random!: number
newGame(imageList: []): void {
    this.random = Math.floor((Math.random()*imageList.length))
}

In template

<img src="assets/uploads/{{random}}">

You don't even need the array if you have a fixed number of images in your resource folder.

CodePudding user response:

As I see in your code you call the newGame() without give him a parameter so you need him to red your global variable imageLest so you need to do this

newGame() {
//console.log("new game");
this.imageList[Math.floor((Math.random()*this.imageList.length))]; 
//imageList = "../assets/images/"   id   png;
}

I hope that's gonna fix your problem

  • Related